package com.sc.nft.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.sc.nft.dao.*;
import com.sc.nft.dto.*;
import com.sc.nft.entity.*;
import com.sc.nft.entity.dto.EcologyHatchCountDTO;
import com.sc.nft.entity.dto.EcologyHatchEffectiveTeamTokenDTO;
import com.sc.nft.enums.*;
import com.sc.nft.exception.GlobalRunTimeException;
import com.sc.nft.service.*;
import com.sc.nft.util.BigDecimalUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@RequiredArgsConstructor
@Service
public class UserEcologyHatchIncomeServiceImpl implements UserEcologyHatchIncomeService {


    private final UserConsensusService userConsensusService;
    private final UserEcologyPointsService userEcologyPointsService;
    private final UserEquityPropsService userEquityPropsService;
    private final EquityPropsService equityPropsService;
    private final UserInfoService userInfoService;
    private final UserEcologyHatchRecordsDao userEcologyHatchRecordsDao;
    private final UserCollectionService userCollectionService;
    private final EcologyCollectionNodeConfDao ecologyCollectionNodeConfDao;
    private final EcologyHatchIncomeConfDao ecologyHatchIncomeConfDao;
    private final UserInfoDao userInfoDao;
    private final UserWorkRoomDao userWorkRoomDao;
    private final UserCityServerCentreDao userCityServerCentreDao;
    private final UserRelevanceDao userRelevanceDao;
    private final EcologyHatchShareIncomeConfDao ecologyHatchShareIncomeConfDao;
    private final EcologyHatchShareProfitDao ecologyHatchShareProfitDao;
    private final DaoIdentityDao daoIdentityDao;
    private final EcologyHatchConfDao ecologyHatchConfDao;
    private final DaoEcologyPointsService daoEcologyPointsService;
    private final EcologyHatchCollecionShareProfitConfDao ecologyHatchCollecionShareProfitConfDao;
    private final DigitalCollectionDao digitalCollectionDao;
    private final UserCreatorInfoDao userCreatorInfoDao;
    private final StaticDataDao staticDataDao;
    private final DaoEcologyMarketValueRecordsDao daoEcologyMarketValueRecordsDao;
    private final UserEcologyNotSettleListDao userEcologyNotSettleListDao;
    private final EcologyHatchShareProfitMethodConfDao ecologyHatchShareProfitMethodConfDao;
    private final MarketManagementDaoPoolService marketManagementDaoPoolService;
    private final ExitConsensusUserDao exitConsensusUserDao;
    private final MarketManagementDaoPoolDao marketManagementDaoPoolDao;
    private final UserPredictEcologyHatchRewardsRecordsDao userPredictEcologyHatchRewardsRecordsDao;
    private final EcologySmeltingService ecologySmeltingService;
    private final EcologyPointsService ecologyPointsService;
    private final UserEcologyPointsWalletService userEcologyPointsWalletService;
    private final EcologyHatchIncomeConfRelevanceDao ecologyHatchIncomeConfRelevanceDao;
    private final NewEcologyHatchShareProfitDao newEcologyHatchShareProfitDao;
    private final EcologyPointsDao ecologyPointsDao;
    private final ShareProfitDaoPoolService shareProfitDaoPoolService;
    private final EcologyShareProfitServiceCenterConfService ecologyShareProfitServiceCenterConfService;
    private final DaoEcologyPointsWalletService daoEcologyPointsWalletService;
    private final EcologyCollectionShareProfitConfDao ecologyCollectionShareProfitConfDao;


    @Override
    public void settleHatch() {
        Date now = new Date();
        Date startTime = DateUtil.beginOfDay(now);
        Date endTime = DateUtil.endOfDay(now);
        //周期奖励
        settlePeriodicReward(startTime, endTime);
        List<UserEcologyHatchRecords> settleList = userEcologyHatchRecordsDao.getSettleList();
        for (UserEcologyHatchRecords userEcologyHatchRecords : settleList) {
            settleDirectThrustIncome(userEcologyHatchRecords);
        }
    }

    @Override
//    @Transactional(rollbackFor = Exception.class)
    public void settlePeriodicReward(Date startTime, Date endTime) {
        // 8月26号之前熔炼产出券 加的共识度
        String typeKey = "consensus_key_";

        List<StaticData> listByType = staticDataDao.getListByType(typeKey);
        Map<String, String> staticDataMap = listByType.stream().collect(Collectors.toMap(StaticData::getType, StaticData::getValue));

        //获取熔炼奖励
        List<UserPredictEcologyHatchRewardsRecords> needIssueList = userPredictEcologyHatchRewardsRecordsDao.getNeedIssueList(startTime, endTime);

        for (UserPredictEcologyHatchRewardsRecords userPredictEcologyHatchRewardsRecords : needIssueList) {
            // 生态孵化配置
            EcologyHatchConf ecologyHatchConf = ecologyHatchConfDao.getById(userPredictEcologyHatchRewardsRecords.getEcologyHatchId());
            UserEcologyExpenditureTypeEnum expenditureType = null;
            EcologyRewardsType rewardsType = null;
            BigDecimal amount = userPredictEcologyHatchRewardsRecords.getLinkCount();
            Long linkId = 0L;
            //生态燃料
            if (userPredictEcologyHatchRewardsRecords.getRewardsType() == EcologyRewardsType.ECOLOGY_POINTS) {
                expenditureType = UserEcologyExpenditureTypeEnum.ECOLOGY_POINTS;
                rewardsType = EcologyRewardsType.ECOLOGY_POINTS;
                //增加生态燃料
                userEcologyPointsService.addEcologyPoints(userPredictEcologyHatchRewardsRecords.getUserId(), amount, EcologyPointsEnum.INCOME, StrUtil.EMPTY);
            } else if (userPredictEcologyHatchRewardsRecords.getRewardsType() == EcologyRewardsType.EQUITY_PROPS) {//权益道具
                //是否额外奖励
                if (!userPredictEcologyHatchRewardsRecords.getExtraReward()) {
                    ExitConsensusUser exitConsensusUser = exitConsensusUserDao.getByUserId(userPredictEcologyHatchRewardsRecords.getUserId());
                    Boolean isConsensus = ObjectUtil.isNull(exitConsensusUser) || !exitConsensusUser.getStatus();
                    if (isConsensus) {
                        UserInfo userInfo = userInfoDao.getById(userPredictEcologyHatchRewardsRecords.getUserId());
                        UserEcologyHatchRecords userEcologyHatchRecords = userEcologyHatchRecordsDao.getById(userPredictEcologyHatchRewardsRecords.getUserEcologyHatchRecordsId());
                        // 要添加的共识
                        Integer total = userPredictEcologyHatchRewardsRecords.getLinkCount().intValue();
                        // 判断用户限制时间内的熔炼组数
                        Boolean coefficient = Boolean.FALSE;
                        Integer limitsTheUserSum = userEcologyHatchRecordsDao.getLimitsTheUserSum(userPredictEcologyHatchRewardsRecords.getUserId());
                        if (limitsTheUserSum > 5) {
                            if (DateUtil.parse("2024-07-01 00:00:00", "yyyy-MM-dd HH:mm:ss").after(userInfo.getCreateTime())) {
                                // 7月1号之前
                                if (DateUtil.parse("2024-08-26 18:00:00", "yyyy-MM-dd HH:mm:ss").after(userEcologyHatchRecords.getCreateTime())) {
                                    // 熔炼记录在26号之前
                                    // 走系数
                                    String needAddStr = staticDataMap.get(typeKey + userPredictEcologyHatchRewardsRecords.getEcologyHatchId());
                                    if (Objects.nonNull(needAddStr)) {
                                        Integer needAdd = BigDecimalUtils.p(needAddStr).intValue();
                                        if (needAdd.intValue() < 1) {
                                            // 走系数
                                            coefficient = Boolean.TRUE;
                                        } else {
                                            // 不走系数
                                            coefficient = Boolean.FALSE;
                                        }
                                    } else {
                                        coefficient = Boolean.FALSE;
                                    }
                                } else {
                                    // 熔炼记录在26号之后
                                    // 不走系数
                                    coefficient = Boolean.FALSE;
                                }
                            } else {
                                // 不走系数
                                coefficient = Boolean.FALSE;
                            }
                        } else {
                            coefficient = Boolean.FALSE;
                        }
                        userConsensusService.adjustConsensusService(userInfo.getId(), ecologyHatchConf.getCollectionId(), BigDecimal.valueOf(total), UserConsensusTypeEnums.SMELT_OUT, userEcologyHatchRecords.getCollectionName(), coefficient);
                    }
                }
                expenditureType = UserEcologyExpenditureTypeEnum.EQUITY_PROPS;
                rewardsType = EcologyRewardsType.EQUITY_PROPS;

                EquityProps equityProps = equityPropsService.getById(userPredictEcologyHatchRewardsRecords.getLinkId());
                linkId = equityProps.getId();

                //查询是否
                UserEcologyNotSettleList notSettleList = userEcologyNotSettleListDao.getLastOneByUserIdAndEquityPropsId(userPredictEcologyHatchRewardsRecords.getUserId(), linkId);
                if (ObjectUtil.isNull(notSettleList)) {
                    //添加权益道具
                    userEquityPropsService.addEquityPropsByUser(equityProps, userPredictEcologyHatchRewardsRecords.getUserId(), UserEquityPropsGetTypeEnum.ECOLOGY_SMELTING_REWARDS, amount.intValue(), StrUtil.format("熔炼:{}", ecologyHatchConf.getCollectionName()),
                            userPredictEcologyHatchRewardsRecords.getUserEcologyHatchRecordsId(), BigDecimal.ZERO, UserEquityPropsGetTypeEnum.ECOLOGY_SMELTING_REWARDS, userPredictEcologyHatchRewardsRecords.getUserEcologyHatchRecordsId());
                } else {

                    //需要偿还的数量大于等于当前奖励数量 则直接扣除
                    if (notSettleList.getFrozenCount() >= notSettleList.getAlreadyCount() + amount.intValue()) {
                        Assert.isTrue(userEcologyNotSettleListDao.addAlreadyCountById(notSettleList.getId(), amount.intValue()), () -> new GlobalRunTimeException("更新次数失败"));

                        UserEcologyNotSettleList newNowSettleRecords = userEcologyNotSettleListDao.getById(notSettleList.getId());
                        if (newNowSettleRecords.getAlreadyCount().intValue() >= newNowSettleRecords.getFrozenCount().intValue()) {
                            Assert.isTrue(userEcologyNotSettleListDao.deleteById(notSettleList.getId()), () -> new GlobalRunTimeException("更新次数失败"));
                        }
                        return;
                    } else {

                        //需要偿还的数量小于当前奖励数量 则扣除剩余的数量
                        int addCount = notSettleList.getAlreadyCount().intValue() + amount.intValue() - notSettleList.getFrozenCount();
                        int remainingCount = notSettleList.getFrozenCount() - notSettleList.getAlreadyCount().intValue();

                        Assert.isTrue(userEcologyNotSettleListDao.addAlreadyCountById(notSettleList.getId(), remainingCount), () -> new GlobalRunTimeException("更新次数失败"));

                        UserEcologyNotSettleList newNowSettleRecords = userEcologyNotSettleListDao.getById(notSettleList.getId());
                        if (newNowSettleRecords.getAlreadyCount().intValue() >= newNowSettleRecords.getFrozenCount().intValue()) {
                            Assert.isTrue(userEcologyNotSettleListDao.deleteById(notSettleList.getId()), () -> new GlobalRunTimeException("更新次数失败"));
                        }
                        if (addCount > 0) {
                            //添加权益道具
                            userEquityPropsService.addEquityPropsByUser(equityProps, userPredictEcologyHatchRewardsRecords.getUserId(), UserEquityPropsGetTypeEnum.ECOLOGY_SMELTING_REWARDS, addCount, StrUtil.format("熔炼:{}", ecologyHatchConf.getCollectionName()),
                                    userPredictEcologyHatchRewardsRecords.getUserEcologyHatchRecordsId(), BigDecimal.ZERO, UserEquityPropsGetTypeEnum.ECOLOGY_SMELTING_REWARDS, userPredictEcologyHatchRewardsRecords.getUserEcologyHatchRecordsId());
                            amount = Convert.toBigDecimal(addCount);
                        }
                    }
                }
            } else if (userPredictEcologyHatchRewardsRecords.getRewardsType() == EcologyRewardsType.ECOLOGY_MARK) {

                expenditureType = UserEcologyExpenditureTypeEnum.ECOLOGY_MARK;
                rewardsType = EcologyRewardsType.ECOLOGY_MARK;
                EcologyPoints ecologyPoints = ecologyPointsService.getById(userPredictEcologyHatchRewardsRecords.getLinkId());
                linkId = ecologyPoints.getId();
                //增加生态积分
                userEcologyPointsWalletService.adjustAmount(userPredictEcologyHatchRewardsRecords.getUserId(), ecologyPoints.getId(), ecologyPoints.getPointsName(), amount, EcologyPointsWalletEnum.INCOME, StrUtil.EMPTY);
            }
            //收入记录表
            UserEcologyExpenditureRecord userEcologyExpenditureRecord = new UserEcologyExpenditureRecord();
            userEcologyExpenditureRecord.setUserId(userPredictEcologyHatchRewardsRecords.getUserId());
            userEcologyExpenditureRecord.setType(expenditureType);
            userEcologyExpenditureRecord.setTypeName(expenditureType.getDescription());
            userEcologyExpenditureRecord.setRemark(StrUtil.format("熔炼:{}", ecologyHatchConf.getCollectionName()));
            userEcologyExpenditureRecord.setLinkId(linkId);
            userEcologyExpenditureRecord.setLinkName(userPredictEcologyHatchRewardsRecords.getLinkName());
            userEcologyExpenditureRecord.setLinkCount(amount);
            userEcologyExpenditureRecord.setDateTime(Convert.toInt(DateUtil.format(DateTime.now(), "yyyyMMdd")));
            userEcologyExpenditureRecord.setLinkImage(userPredictEcologyHatchRewardsRecords.getLinkImage());
            userEcologyExpenditureRecord.insert();

            //用户奖励记录表
            UserEcologyHatchRewardsRecords userEcologyHatchRewardsRecords = new UserEcologyHatchRewardsRecords();
            userEcologyHatchRewardsRecords.setUserId(userPredictEcologyHatchRewardsRecords.getUserId());
            userEcologyHatchRewardsRecords.setUserEcologyHatchRecordsId(userPredictEcologyHatchRewardsRecords.getUserEcologyHatchRecordsId());
            userEcologyHatchRewardsRecords.setEcologyHatchId(userPredictEcologyHatchRewardsRecords.getEcologyHatchId());
            userEcologyHatchRewardsRecords.setRewardsType(rewardsType);
            userEcologyHatchRewardsRecords.setRewardsTypeName(rewardsType.getDescription());
            userEcologyHatchRewardsRecords.setIncomeType(EcologyIncomeTypeEnum.CYCLE_INCOME);
            userEcologyHatchRewardsRecords.setIncomeTypeName(EcologyIncomeTypeEnum.CYCLE_INCOME.getDescription());
            userEcologyHatchRewardsRecords.setLinkId(linkId);
            userEcologyHatchRewardsRecords.setLinkName(userPredictEcologyHatchRewardsRecords.getLinkName());
            userEcologyHatchRewardsRecords.setLinkCount(amount);
            userEcologyHatchRewardsRecords.setLinkImge(userPredictEcologyHatchRewardsRecords.getLinkImage());
            userEcologyHatchRewardsRecords.insert();
            userPredictEcologyHatchRewardsRecordsDao.updateStatusById(userPredictEcologyHatchRewardsRecords.getId(), Boolean.TRUE);
        }
    }

    private void settleDirectThrustIncome(UserEcologyHatchRecords oldRecords) {
        //进行中的订单 周期+1天
        Assert.isTrue(userEcologyHatchRecordsDao.addAlreadyDayByStatusById(oldRecords.getId()), () -> new GlobalRunTimeException("更新天数失败"));
//        //获取加了之后的记录
        UserEcologyHatchRecords userEcologyHatchRecords = userEcologyHatchRecordsDao.getById(oldRecords.getId());
        //如果当前已经产出的时间大于等于周期时间 则修改为已完成
        UserEcologyHatchRecords newRecords = userEcologyHatchRecordsDao.getById(userEcologyHatchRecords.getId());
        if (newRecords.getAlreadyDay() >= userEcologyHatchRecords.getHatchCycle()) {
            EcologyHatchCountDTO userHatchCount = ecologySmeltingService.getUserHatchCount(newRecords.getUserId(), userEcologyHatchRecords.getEcologyHatchId());
            //修改为已完成
            Assert.isTrue(userEcologyHatchRecordsDao.updateStatusById(userEcologyHatchRecords.getId()), () -> new GlobalRunTimeException("更新状态失败"));

            UserEcologyHatchUpperLimitDetails userEcologyHatchUpperLimitDetails = new UserEcologyHatchUpperLimitDetails();
            userEcologyHatchUpperLimitDetails.setUserId(newRecords.getUserId());
            userEcologyHatchUpperLimitDetails.setCollectionId(userEcologyHatchRecords.getCollectionId());
            userEcologyHatchUpperLimitDetails.setUserRecordsId(0L);
            userEcologyHatchUpperLimitDetails.setType(UserEcologyHatchUpperLimitDetailsTypeEnum.HATCH_RELEASE);
            userEcologyHatchUpperLimitDetails.setTypeName(UserEcologyHatchUpperLimitDetailsTypeEnum.HATCH_RELEASE.getDescription());
            userEcologyHatchUpperLimitDetails.setUseCount(userEcologyHatchRecords.getHatchCount());
            userEcologyHatchUpperLimitDetails.setBeforeCount(userHatchCount.getSumRemainingCount());
            userEcologyHatchUpperLimitDetails.setAfterCount(userHatchCount.getSumRemainingCount() + newRecords.getHatchCount());
            userEcologyHatchUpperLimitDetails.setIsAdd(UserEcologyHatchUpperLimitDetailsTypeEnum.HATCH_RELEASE.getIsAdd());
            userEcologyHatchUpperLimitDetails.insert();

        }
        //计算直推
        //1.当前在进行装
        //2.直推收益配置
        //3.订单时间不在当天
        if (newRecords.getStatus() == UserEcologyHatchRecordsStatus.UNDER_WAY
                && EcologyHatchDirectThrustIncomeType.getIncomeTypeList().contains(newRecords.getIsSettleDirectThrustIncome())
                && newRecords.getCreateTime().before(DateUtil.beginOfDay(DateTime.now()))) {
            //直推收益
            List<NewEcologyHatchShareProfit> newEcologyHatchShareProfits = newEcologyHatchShareProfitDao.getByUserRecordId(oldRecords.getId(), EcologyCollectionShareProfitTypeEnum.SHARE_PROFIT);
            //结算
            newSettleDirectThrustIncomeList(userEcologyHatchRecords, newEcologyHatchShareProfits);
        }
    }


    /**
     * 结算直推收益(新)
     *
     * @param newEcologyHatchShareProfits
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void newSettleDirectThrustIncomeList(UserEcologyHatchRecords userEcologyHatchRecords, List<NewEcologyHatchShareProfit> newEcologyHatchShareProfits) {
        if (CollectionUtils.isEmpty(newEcologyHatchShareProfits)) {
            userEcologyHatchRecordsDao.updateIsSettleDirectThrustIncomeById(userEcologyHatchRecords.getId(), EcologyHatchDirectThrustIncomeType.NOT_FOUND_CONF);
            return;
        }
        NewEcologyHatchShareProfit newEcologyHatchShareProfit = newEcologyHatchShareProfits.get(0);

        Long recommendUserId = userEcologyHatchRecords.getRecommendUserId();
        if (recommendUserId.intValue() == 0 || recommendUserId.intValue() == 1) {
            UserInfo user = userInfoService.getById(userEcologyHatchRecords.getUserId());

            UserInfo recommendUser = userInfoService.getById(user.getRecommendUserId());
            if (ObjectUtil.isNull(recommendUser)) {
                userEcologyHatchRecordsDao.updateIsSettleDirectThrustIncomeById(userEcologyHatchRecords.getId(), EcologyHatchDirectThrustIncomeType.NOT_FOUND_RECOMMEND_USER);
                return;
            }

            recommendUserId = recommendUser.getId();
        }

        //获取这个生态熔炼的下配置有直推收益的藏品
        List<Long> collectionIds = ecologyHatchShareIncomeConfDao.getCollectionIdsByConfId(userEcologyHatchRecords.getEcologyHatchId());
        if (collectionIds.size() == 0) {
            userEcologyHatchRecordsDao.updateIsSettleDirectThrustIncomeById(userEcologyHatchRecords.getId(), EcologyHatchDirectThrustIncomeType.NOT_FOUND_INCOME_COLLECTION);
            return;
        }
        //判断用户市场持有居民、城主或生态节点藏品
        //23-12-13 修改为配置的藏品
        Boolean isSettle = isSettleDirectThrustIncome(recommendUserId, collectionIds);
        if (isSettle) {
            EcologyPoints ecologyPoints = ecologyPointsService.getById(newEcologyHatchShareProfit.getPointsId());
            //增加生态积分
            userEcologyPointsWalletService.adjustAmount(recommendUserId, ecologyPoints.getId(), ecologyPoints.getPointsName(),
                    newEcologyHatchShareProfit.getDistributionPoints(), EcologyPointsWalletEnum.RECOMMENDED_INCOME, EcologyPointsWalletEnum.RECOMMENDED_INCOME.getDescription());

            //收入记录表
            UserEcologyExpenditureRecord userEcologyExpenditureRecord = new UserEcologyExpenditureRecord();
            userEcologyExpenditureRecord.setUserId(recommendUserId);
            userEcologyExpenditureRecord.setType(UserEcologyExpenditureTypeEnum.ECOLOGY_MARK);
            userEcologyExpenditureRecord.setTypeName(UserEcologyExpenditureTypeEnum.ECOLOGY_MARK.getDescription());
            userEcologyExpenditureRecord.setRemark(newEcologyHatchShareProfit.getTypeName());
            userEcologyExpenditureRecord.setLinkId(0L);
            userEcologyExpenditureRecord.setDateTime(Convert.toInt(DateUtil.format(DateTime.now(), "yyyyMMdd")));
            userEcologyExpenditureRecord.setLinkName(StrUtil.EMPTY);
            userEcologyExpenditureRecord.setLinkCount(newEcologyHatchShareProfit.getDistributionPoints());
            userEcologyExpenditureRecord.setLinkImage(StrUtil.EMPTY);
            userEcologyExpenditureRecord.insert();

            //用户奖励记录表
            UserEcologyHatchRewardsRecords userEcologyHatchRewardsRecords = new UserEcologyHatchRewardsRecords();
            userEcologyHatchRewardsRecords.setUserId(recommendUserId);
            userEcologyHatchRewardsRecords.setUserEcologyHatchRecordsId(userEcologyHatchRecords.getId());
            userEcologyHatchRewardsRecords.setEcologyHatchId(userEcologyHatchRecords.getEcologyHatchId());
            userEcologyHatchRewardsRecords.setRewardsType(EcologyRewardsType.ECOLOGY_MARK);
            userEcologyHatchRewardsRecords.setRewardsTypeName(EcologyRewardsType.ECOLOGY_MARK.getDescription());
            userEcologyHatchRewardsRecords.setIncomeType(EcologyIncomeTypeEnum.RECOMMENDED_INCOME);
            userEcologyHatchRewardsRecords.setIncomeTypeName(EcologyIncomeTypeEnum.RECOMMENDED_INCOME.getDescription());
            userEcologyHatchRewardsRecords.setLinkId(0L);
            userEcologyHatchRewardsRecords.setLinkName(EcologyRewardsType.ECOLOGY_POINTS.getDescription());
            userEcologyHatchRewardsRecords.setLinkCount(newEcologyHatchShareProfit.getDistributionPoints());
            userEcologyHatchRewardsRecords.setLinkImge(StrUtil.EMPTY);
            userEcologyHatchRewardsRecords.insert();

            newEcologyHatchShareProfitDao.updateSettleStatusById(newEcologyHatchShareProfit.getId(), NewEcologyHatchShareProfitStatus.PROCESSING_SUCCESS, null);
            //修改为结算成功
            userEcologyHatchRecordsDao.updateIsSettleDirectThrustIncomeById(userEcologyHatchRecords.getId(), EcologyHatchDirectThrustIncomeType.HAVE_ALREADY_SETTLED);
        } else {
            userEcologyHatchRecordsDao.updateIsSettleDirectThrustIncomeById(userEcologyHatchRecords.getId(), EcologyHatchDirectThrustIncomeType.FAIL);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void settleDirectThrustIncomeList(UserEcologyHatchRecords userEcologyHatchRecords, EcologyHatchCollecionShareProfitConf incomeConf) {
        if (ObjectUtil.isNull(incomeConf)) {
            userEcologyHatchRecordsDao.updateIsSettleDirectThrustIncomeById(userEcologyHatchRecords.getId(), EcologyHatchDirectThrustIncomeType.NOT_FOUND_CONF);
            return;
        }

        Long recommendUserId = userEcologyHatchRecords.getRecommendUserId();
        if (recommendUserId.intValue() == 0 || recommendUserId.intValue() == 1) {
            UserInfo user = userInfoService.getById(userEcologyHatchRecords.getUserId());

            UserInfo recommendUser = userInfoService.getById(user.getRecommendUserId());
            if (ObjectUtil.isNull(recommendUser)) {
                userEcologyHatchRecordsDao.updateIsSettleDirectThrustIncomeById(userEcologyHatchRecords.getId(), EcologyHatchDirectThrustIncomeType.NOT_FOUND_RECOMMEND_USER);
                return;
            }

            recommendUserId = recommendUser.getId();
        }

        //获取这个生态熔炼的下配置有直推收益的藏品
        List<Long> collectionIds = ecologyHatchShareIncomeConfDao.getCollectionIdsByConfId(userEcologyHatchRecords.getEcologyHatchId());
        if (collectionIds.size() == 0) {
            userEcologyHatchRecordsDao.updateIsSettleDirectThrustIncomeById(userEcologyHatchRecords.getId(), EcologyHatchDirectThrustIncomeType.NOT_FOUND_INCOME_COLLECTION);
            return;
        }
        //判断用户市场持有居民、城主或生态节点藏品
        //23-12-13 修改为配置的藏品
        Boolean isSettle = isSettleDirectThrustIncome(recommendUserId, collectionIds);
        if (isSettle) {
            BigDecimal ecologyPoints = userEcologyHatchRecords.getEcologyPoints();
            BigDecimal incomeScale = incomeConf.getDistributionScale().movePointLeft(2);
            BigDecimal amount = ecologyPoints.multiply(incomeScale).setScale(2, BigDecimal.ROUND_DOWN);

            //增加生态燃料
            userEcologyPointsService.addDynamicStateEcologyPoints(recommendUserId, amount, EcologyPointsEnum.RECOMMENDED_INCOME, EcologyIncomeTypeEnum.RECOMMENDED_INCOME, StrUtil.EMPTY, StrUtil.EMPTY);

            //收入记录表
            UserEcologyExpenditureRecord userEcologyExpenditureRecord = new UserEcologyExpenditureRecord();
            userEcologyExpenditureRecord.setUserId(recommendUserId);
            userEcologyExpenditureRecord.setType(UserEcologyExpenditureTypeEnum.ECOLOGY_POINTS);
            userEcologyExpenditureRecord.setTypeName(UserEcologyExpenditureTypeEnum.ECOLOGY_POINTS.getDescription());
            userEcologyExpenditureRecord.setRemark(incomeConf.getTypeName());
            userEcologyExpenditureRecord.setLinkId(0L);
            userEcologyExpenditureRecord.setDateTime(Convert.toInt(DateUtil.format(DateTime.now(), "yyyyMMdd")));
            userEcologyExpenditureRecord.setLinkName(StrUtil.EMPTY);
            userEcologyExpenditureRecord.setLinkCount(amount);
            userEcologyExpenditureRecord.setLinkImage(StrUtil.EMPTY);
            userEcologyExpenditureRecord.insert();

            //用户奖励记录表
            UserEcologyHatchRewardsRecords userEcologyHatchRewardsRecords = new UserEcologyHatchRewardsRecords();
            userEcologyHatchRewardsRecords.setUserId(recommendUserId);
            userEcologyHatchRewardsRecords.setUserEcologyHatchRecordsId(userEcologyHatchRecords.getId());
            userEcologyHatchRewardsRecords.setEcologyHatchId(userEcologyHatchRecords.getEcologyHatchId());
            userEcologyHatchRewardsRecords.setRewardsType(EcologyRewardsType.ECOLOGY_POINTS);
            userEcologyHatchRewardsRecords.setRewardsTypeName(EcologyRewardsType.ECOLOGY_POINTS.getDescription());
            userEcologyHatchRewardsRecords.setIncomeType(EcologyIncomeTypeEnum.RECOMMENDED_INCOME);
            userEcologyHatchRewardsRecords.setIncomeTypeName(EcologyIncomeTypeEnum.RECOMMENDED_INCOME.getDescription());
            userEcologyHatchRewardsRecords.setLinkId(0L);
            userEcologyHatchRewardsRecords.setLinkName(EcologyRewardsType.ECOLOGY_POINTS.getDescription());
            userEcologyHatchRewardsRecords.setLinkCount(amount);
            userEcologyHatchRewardsRecords.setLinkImge(StrUtil.EMPTY);
            userEcologyHatchRewardsRecords.insert();


            //收益记录表
            UserEcologyHatchIncomeRecord userEcologyHatchIncomeRecord = new UserEcologyHatchIncomeRecord();
            userEcologyHatchIncomeRecord.setAmount(amount);
            userEcologyHatchIncomeRecord.setUserId(recommendUserId);
            userEcologyHatchIncomeRecord.setIncomeType(EcologyIncomeTypeEnum.RECOMMENDED_INCOME);
            userEcologyHatchIncomeRecord.setIncomeTypeName(EcologyIncomeTypeEnum.RECOMMENDED_INCOME.getDescription());
            userEcologyHatchIncomeRecord.setSourceUserId(userEcologyHatchRecords.getUserId());
            userEcologyHatchIncomeRecord.setOurceUserEcologyHatchRecordsId(userEcologyHatchRecords.getId());
            userEcologyHatchIncomeRecord.setSumPrizePool(ecologyPoints);
            userEcologyHatchIncomeRecord.setPrizePoolScale(incomeScale);
            userEcologyHatchIncomeRecord.setSumHeadCountCollectionNode(0L);
            userEcologyHatchIncomeRecord.setRecommendHeadCountCollectionNode(0L);
            userEcologyHatchIncomeRecord.insert();

            //修改为结算成功
            userEcologyHatchRecordsDao.updateIsSettleDirectThrustIncomeById(userEcologyHatchRecords.getId(), EcologyHatchDirectThrustIncomeType.HAVE_ALREADY_SETTLED);
        } else {
            userEcologyHatchRecordsDao.updateIsSettleDirectThrustIncomeById(userEcologyHatchRecords.getId(), EcologyHatchDirectThrustIncomeType.FAIL);
        }

    }

    /**
     * 生态节点持仓奖
     * <p>
     * 前置条件：
     * 1.持有生态节点藏品；
     * 2.生态节点藏品持有者当前正在参与生态熔炼（有当前正在进行中的记录）
     * <p>
     * 计算公式：
     * 1）生态节点持仓奖=持有生态节点藏品数量/全平台生态节点藏品数量*配置比例*分红池
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void ecologyNodeTakePsitionIncome() {
        //获取生态节点藏品集合
        List<Long> collectionIds = ecologyCollectionNodeConfDao.getCollectionList();
        if (CollUtil.isEmpty(collectionIds)) {
            return;
        }

        //上周平台分红池
        BigDecimal bonusPool = getLastWeekBonusPool(DaoInfoEnum.META_DAO.getId(), EcologyHatchShareProfitTypeEnum.PLATFORM_DIVIDE);

        //持有生态的用户
        List<Long> userIds = userCollectionService.getUserListByCollectionIds(collectionIds);
        ArrayList<UserHoldCollectionDTO> settleUser = Lists.newArrayList();
        //判断用户是否符合条件
        for (Long userId : userIds) {

            //用户个人持有数量
            Integer holdCount = userCollectionService.getHoldCountByCollectionIdsAndUserId(userId, collectionIds);
            //累加平台持有量
//            sumHoldCount += holdCount;

            //判断用户是否有进行中的记录
            Boolean underWayUser = userEcologyHatchRecordsDao.getBooleanByStatusAndUserId(userId, UserEcologyHatchRecordsStatus.UNDER_WAY);
            if (holdCount > 0 && underWayUser) {
                UserHoldCollectionDTO userHoldCollectionDTO = new UserHoldCollectionDTO();
                userHoldCollectionDTO.setUserId(userId);
                userHoldCollectionDTO.setHoldCount(holdCount);
                settleUser.add(userHoldCollectionDTO);
            }

        }

        EcologyHatchIncomeConf ecologicalNodePositionAward = ecologyHatchIncomeConfDao.getOneByType(EcologyIncomeTypeEnum.ECOLOGICAL_NODE_POSITION_AWARD);
        BigDecimal incomeScale = ecologicalNodePositionAward.getIncomeScale().movePointLeft(2);

        //12-27 统计维度修改为持有有效的条件的人数总和
        Integer sumHoldCount = settleUser.stream().mapToInt(o -> Objects.isNull(o.getHoldCount()) ? 0 : o.getHoldCount()).sum();

        if (sumHoldCount > 0
                && NumberUtil.isGreater(incomeScale, BigDecimal.ZERO)
                && NumberUtil.isGreater(bonusPool, BigDecimal.ZERO)) {
            //结算收益
            settleEcologyNodeTakePsitionIncome(settleUser, sumHoldCount, incomeScale, bonusPool);
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void daoPositionBonusAward(EcologyHatchDaoIncomeConf ecologyHatchDaoIncomeConf) {
        Long holdCollectionId = ecologyHatchDaoIncomeConf.getHoldCollectionId();
        if (ObjectUtil.isNull(holdCollectionId)) {
            return;
        }

        DigitalCollection collection = digitalCollectionDao.getById(holdCollectionId);
        if (ObjectUtil.isNull(collection)) {
            return;
        }

        //上周分红池
        BigDecimal bonusPool = getLastWeekBonusPool(ecologyHatchDaoIncomeConf.getDaoId(), EcologyHatchShareProfitTypeEnum.DAO_DIVIDE);
        if (!NumberUtil.isGreater(bonusPool, BigDecimal.ZERO)) {
            return;
        }


        //持有的身份卡
        List<Long> daoIdentityCollectionIds = Arrays.asList(ecologyHatchDaoIncomeConf.getCollectionId());
        //持有的藏品
        List<Long> holdCollectionIds = Arrays.asList(ecologyHatchDaoIncomeConf.getHoldCollectionId());

        //持有藏品的用户
        List<Long> userIds = userCollectionService.getUserListByCollectionIds(daoIdentityCollectionIds);
        if (CollUtil.isEmpty(userIds)) {
            return;
        }

        //需要熔炼的藏品
        List<Long> ecologyHatchcollectionIds = ecologyHatchConfDao.getEcologyHatchCollectonListByDaoId(ecologyHatchDaoIncomeConf.getDaoId());
        if (ecologyHatchcollectionIds.size() == 0) {
            return;
        }

        ArrayList<UserHoldCollectionDTO> settleUser = Lists.newArrayList();
        for (Long userId : userIds) {

            //用户个人持有数量
            Integer holdCount = userCollectionService.getHoldCountByCollectionIdsAndUserId(userId, holdCollectionIds);

            //判断用户是否有进行中的记录(指定熔炼的藏品)
            Boolean underWayUser = userEcologyHatchRecordsDao.getBooleanByStatusAndUserIdAndCollectionIds(userId, ecologyHatchcollectionIds, UserEcologyHatchRecordsStatus.UNDER_WAY);
            if (holdCount > 0 && underWayUser) {
                UserHoldCollectionDTO userHoldCollectionDTO = new UserHoldCollectionDTO();
                userHoldCollectionDTO.setUserId(userId);
                userHoldCollectionDTO.setHoldCount(holdCount);
                settleUser.add(userHoldCollectionDTO);
            }
        }

        Integer sumHoldCount = settleUser.stream().mapToInt(o -> Objects.isNull(o.getHoldCount()) ? 0 : o.getHoldCount()).sum();
        BigDecimal incomeScale = ecologyHatchDaoIncomeConf.getIncomeScale().movePointLeft(2);
        if (sumHoldCount > 0
                && NumberUtil.isGreater(incomeScale, BigDecimal.ZERO)
                && NumberUtil.isGreater(bonusPool, BigDecimal.ZERO)) {
            //结算收益
            settleDaoEcologyNodeTakePsitionIncome(settleUser, sumHoldCount, incomeScale, bonusPool, ecologyHatchDaoIncomeConf.getDividendIncomeName());
        }

    }


    /**
     * 生态城主贡献奖
     * 前置条件：
     * 1.持有城主藏品；
     * 2.城主用户当前正在参与生态熔炼（有当前正在进行中的记录）
     * 3.直推至少3个城主，且3个城主都参与生态熔炼（有当前正在进行中的记录）
     * <p>
     * 计算公式：
     * 1）生态贡献奖（365天）=最近365天团队内生态熔炼投入生态燃料/最近365天全平台投入生态熔炼的生态燃料*配置比例*分红池
     * 2）生态贡献奖（7天）=最近7天团队内生态熔炼投入生态燃料/最近7天全平台生态熔炼投入生态燃料*配置比例*分红池
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void ecologyContributionIncome() {
        //分红池 7天内所有用户参与生态熔炼的总燃料(不包含当天的7天)
//        BigDecimal bonusPool = userEcologyHatchRecordsDao.getBonusPool(7);
        //上周平台分红池
        BigDecimal bonusPool = getLastWeekBonusPool(DaoInfoEnum.META_DAO.getId(), EcologyHatchShareProfitTypeEnum.PLATFORM_DIVIDE);
        //节点藏品信息
        List<Long> nodeCollectionIds = ecologyCollectionNodeConfDao.getCollectionList();
        if (CollUtil.isNotEmpty(nodeCollectionIds)) {
            //生态节点
            settleEcologyContributionIncome(bonusPool, nodeCollectionIds, EcologyIncomeTypeEnum.NODE_CONTRIBUTION_AWARD_365, EcologyIncomeTypeEnum.NODE_CONTRIBUTION_AWARD_7, EcologyPointsEnum.NODE_CONTRIBUTION_AWARD_365, EcologyPointsEnum.NODE_CONTRIBUTION_AWARD_7);
        }
        //城主id
        List<Long> collectionIds = Arrays.asList(SpecialIdEnum.CITY_LORD_ID.getCollectionId());
        //城主
        settleEcologyContributionIncome(bonusPool, collectionIds, EcologyIncomeTypeEnum.CONTRIBUTION_AWARD_365, EcologyIncomeTypeEnum.CONTRIBUTION_AWARD_7, EcologyPointsEnum.CONTRIBUTION_AWARD_365, EcologyPointsEnum.CONTRIBUTION_AWARD_7);
    }

    /**
     * DAO贡献奖
     * 前置条件：
     * 1.持有配置的身份卡藏品；
     * 2.用户当前正在参与生态熔炼（有当前正在进行中的记录）
     * 3.直推至少X个持有配置的身份卡，且X个用户都参与生态熔炼（有当前正在进行中的记录，X取直推人数配置）
     * <p>
     * 计算公式：
     * 1）DAO贡献奖（365天）= 最近365天团队内生态熔炼该DAO藏品的生态燃料（扣除最大直推团队投入） / 最近365天全平台熔炼该DAO藏品的生态燃料 * 配置比例 * 分红池
     * 1）DAO贡献奖（7天）= 上周一到上周日团队内生态熔炼该DAO藏品的生态燃料（扣除最大直推团队投入） / 上周一到上周日全平台熔炼该DAO藏品的生态燃料 * 配置比例 * 分红池
     *
     * @param ecologyHatchDaoIncomeConf
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void daoEcologyContributionIncome(EcologyHatchDaoIncomeConf ecologyHatchDaoIncomeConf) {
        //上周分红池
        BigDecimal bonusPool = getLastWeekBonusPool(ecologyHatchDaoIncomeConf.getDaoId(), EcologyHatchShareProfitTypeEnum.DAO_DIVIDE);
        if (!NumberUtil.isGreater(bonusPool, BigDecimal.ZERO)) {
            return;
        }


        //获取持有藏品的用户
        List<Long> holdCollectionIds = Arrays.asList(ecologyHatchDaoIncomeConf.getCollectionId());
        List<Long> userIds = userCollectionService.getUserListByCollectionIds(Arrays.asList(ecologyHatchDaoIncomeConf.getCollectionId()));
        if (CollUtil.isEmpty(userIds)) {
            return;
        }

        //需要熔炼的藏品
        List<Long> ecologyHatchcollectionIds = ecologyHatchConfDao.getEcologyHatchCollectonListByDaoId(ecologyHatchDaoIncomeConf.getDaoId());
        if (ecologyHatchcollectionIds.size() == 0) {
            return;
        }

        List<Long> settleUser = checkDaoEcologyNodeContributionIncome(userIds, holdCollectionIds, ecologyHatchDaoIncomeConf.getDirectThrustUserCount());
        if (CollUtil.isEmpty(settleUser)) {
            return;
        }

        BigDecimal incomeScale = ecologyHatchDaoIncomeConf.getIncomeScale().movePointLeft(2);
        //统计维度
        int days = ecologyHatchDaoIncomeConf.getDimensionality().getDays();

        ArrayList<EcologyHatchEffectiveTeamTokenDTO> settleList = Lists.newArrayList();
        BigDecimal platformSum = BigDecimal.ZERO;
        for (Long userId : settleUser) {
            EcologyHatchEffectiveTeamTokenDTO effectiveTeamTokendto = getDaoEffectiveTeamToken(userId, ecologyHatchcollectionIds, days);
            if (NumberUtil.isGreater(effectiveTeamTokendto.getTeamToken365(), BigDecimal.ZERO)) {
                platformSum = platformSum.add(effectiveTeamTokendto.getTeamToken365());
                settleList.add(effectiveTeamTokendto);
            }
        }

        for (EcologyHatchEffectiveTeamTokenDTO ecologyHatchEffectiveTeamTokenDTO : settleList) {
            BigDecimal teamToken = ecologyHatchEffectiveTeamTokenDTO.getTeamToken365();
            if (NumberUtil.isGreater(teamToken, BigDecimal.ZERO)
                    && NumberUtil.isGreater(platformSum, BigDecimal.ZERO)
                    && NumberUtil.isGreater(bonusPool, BigDecimal.ZERO)) {
                addDaoecologyNodeContributionIncome(teamToken, platformSum, incomeScale, bonusPool, ecologyHatchEffectiveTeamTokenDTO.getUserId(), ecologyHatchDaoIncomeConf, EcologyIncomeTypeEnum.DAO_CONTRIBUTION_AWARD, EcologyPointsEnum.DAO_CONTRIBUTION_AWARD, ecologyHatchDaoIncomeConf.getDaoId());
            }
        }
    }

    /**
     * 结算贡献奖
     *
     * @param bonusPool
     * @param collectionIds
     * @param incomeTypeEnum365
     * @param incomeTypeEnum7
     * @param ecologyPointsEnum365
     * @param ecologyPointsEnum7
     */
    private void settleEcologyContributionIncome(BigDecimal bonusPool, List<Long> collectionIds, EcologyIncomeTypeEnum incomeTypeEnum365, EcologyIncomeTypeEnum incomeTypeEnum7, EcologyPointsEnum ecologyPointsEnum365, EcologyPointsEnum ecologyPointsEnum7) {

        List<Long> userIdList = userCollectionService.getUserListByCollectionIds(collectionIds);
        if (CollUtil.isEmpty(userIdList)) {
            return;
        }
        List<Long> userIds = checkEcologyNodeContributionIncome(userIdList, collectionIds);

        if (CollUtil.isEmpty(userIds)) {
            log.info("生态:{}贡献奖:没有需要结算的用户", incomeTypeEnum365.getStanding());
            return;
        }

        //获取 最近365天平台用户生态熔炼投入生态燃料(不包含当天的前365天)

        EcologyHatchIncomeConf contributionAward365 = ecologyHatchIncomeConfDao.getOneByType(incomeTypeEnum365);
        EcologyHatchIncomeConf contributionAward7 = ecologyHatchIncomeConfDao.getOneByType(incomeTypeEnum7);
        BigDecimal incomeScale365 = contributionAward365.getIncomeScale().movePointLeft(2);
        BigDecimal incomeScale7 = contributionAward7.getIncomeScale().movePointLeft(2);

        List<EcologyHatchEffectiveTeamTokenDTO> settleList = Lists.newArrayList();

        BigDecimal teamHoldTokenYear = BigDecimal.ZERO;
        BigDecimal teamHoldTokenDay = BigDecimal.ZERO;

        for (Long userId : userIds) {
            EcologyHatchEffectiveTeamTokenDTO effectiveTeamTokendto = getEffectiveTeamToken(userId);
            settleList.add(effectiveTeamTokendto);
            teamHoldTokenYear = teamHoldTokenYear.add(effectiveTeamTokendto.getTeamToken365());
            teamHoldTokenDay = teamHoldTokenDay.add(effectiveTeamTokendto.getTeamToken7());
        }


        for (EcologyHatchEffectiveTeamTokenDTO ecologyHatchEffectiveTeamTokenDTO : settleList) {
            BigDecimal effectiveTeamToken365 = ecologyHatchEffectiveTeamTokenDTO.getTeamToken365();
            if (NumberUtil.isGreater(incomeScale365, BigDecimal.ZERO)
                    && NumberUtil.isGreater(effectiveTeamToken365, BigDecimal.ZERO)
                    && NumberUtil.isGreater(teamHoldTokenYear, BigDecimal.ZERO)
                    && NumberUtil.isGreater(bonusPool, BigDecimal.ZERO)) {
                //365天的收益
                addecologyNodeContributionIncome(effectiveTeamToken365, teamHoldTokenYear, incomeScale365, bonusPool, ecologyHatchEffectiveTeamTokenDTO.getUserId(), incomeTypeEnum365, ecologyPointsEnum365);
            }


            BigDecimal effectiveTeamToken7 = ecologyHatchEffectiveTeamTokenDTO.getTeamToken7();
            if (NumberUtil.isGreater(incomeScale7, BigDecimal.ZERO)
                    && NumberUtil.isGreater(effectiveTeamToken7, BigDecimal.ZERO)
                    && NumberUtil.isGreater(teamHoldTokenDay, BigDecimal.ZERO)
                    && NumberUtil.isGreater(bonusPool, BigDecimal.ZERO)) {
                //7天的收益
                addecologyNodeContributionIncome(effectiveTeamToken7, teamHoldTokenDay, incomeScale7, bonusPool, ecologyHatchEffectiveTeamTokenDTO.getUserId(), incomeTypeEnum7, ecologyPointsEnum7);
            }
        }


    }


    /**
     * 培育奖
     * 前置条件：
     * 1.持有城主/节点藏品；
     * 2.城主用户当前正在参与生态熔炼（有当前正在进行中的记录）
     * <p>
     * 计算公式：
     * 1）生态培育奖（365天）=下一级是(城主或者生态节点)并且有熔炼记录在365天内的人数/最近365天内有熔炼记录并且是(城主或者生态节点)的人数*配置比例*分红池
     * 2）生态培育奖（7天）= 下一级是(城主或者生态节点)并且有熔炼记录在7天内的人数/最近7天内有熔炼记录并且是(城主或者生态节点)的人数*配置比例*分红池
     * <p>
     * 人话:
     * 1）生态培育奖（365天）=下一级是(城主或者生态节点)并且有熔炼记录在365天内的人数/最近365天内有熔炼记录并且是(城主或者生态节点)的人数*配置比例*分红池
     * 2）生态培育奖（7天）= 下一级是(城主或者生态节点)并且有熔炼记录在7天内的人数/最近7天内有熔炼记录并且是(城主或者生态节点)的人数*配置比例*分红池
     * <p>
     * bonusPool 分红池
     * collectionIds 持有藏品  节点藏品结合/城主
     * income 收益类型
     * ecologyPointsEnum 积分类型
     * day 天数 7或者365
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void ecologyCultivateIncome() {
        //分红池 7天内所有用户参与生态熔炼的总燃料(不包含当天的7天)
//        BigDecimal bonusPool = userEcologyHatchRecordsDao.getBonusPool(7);
        //上周平台分红池
        BigDecimal bonusPool = getLastWeekBonusPool(DaoInfoEnum.META_DAO.getId(), EcologyHatchShareProfitTypeEnum.PLATFORM_DIVIDE);
//        BigDecimal bonusPool = ecologyHatchShareProfitDao.getLastWeekBonusPool(DaoInfoEnum.META_DAO.getId(), EcologyHatchShareProfitTypeEnum.PLATFORM_DIVIDE);
        if (!NumberUtil.isGreater(bonusPool, BigDecimal.ZERO)) {
            return;
        }

        //持有指定藏品 最近天数 新增熔炼记录的人数

        //获取生态节点藏品集合
        List<Long> nodeCollectionIds = ecologyCollectionNodeConfDao.getCollectionList();
        //生态节点藏品
        if (CollUtil.isNotEmpty(nodeCollectionIds)) {
            //365
            settleEcologyCultivateIncome(bonusPool, nodeCollectionIds, EcologyIncomeTypeEnum.NODE_CULTIVATION_AWARD_365, EcologyPointsEnum.NODE_CULTIVATION_AWARD_365);
            //7天
            settleEcologyCultivateIncome(bonusPool, nodeCollectionIds, EcologyIncomeTypeEnum.NODE_CULTIVATION_AWARD_7, EcologyPointsEnum.NODE_CULTIVATION_AWARD_7);
        }
        //城主
        List<Long> collectionIds = Arrays.asList(SpecialIdEnum.CITY_LORD_ID.getCollectionId());
        //365
        settleEcologyCultivateIncome(bonusPool, collectionIds, EcologyIncomeTypeEnum.ECOLOGICAL_CULTIVATION_AWARD_365, EcologyPointsEnum.ECOLOGICAL_CULTIVATION_AWARD_365);
        //7天
        settleEcologyCultivateIncome(bonusPool, collectionIds, EcologyIncomeTypeEnum.ECOLOGICAL_CULTIVATION_AWARD_7, EcologyPointsEnum.ECOLOGICAL_CULTIVATION_AWARD_7);
    }

    /**
     * DAO培育奖
     * <p>
     * 前置条件：
     * <p>
     * 1.持有配置的身份卡藏品；
     * 2.用户当前正在参与生态熔炼（有当前正在进行中的记录）
     * 3.直推至少X个持有配置的身份卡，且X个用户都参与生态熔炼（有当前正在进行中的记录，X取直推人数配置）
     * <p>
     * 计算公式：
     * DAO培育奖（365天）= 最近365天直推持有配置的身份卡参与生态熔炼该DAO藏品的人数 / 最近365天持有配置的身份卡参与生态熔炼该DAO藏品的人数 * 配置比例 * 分红池
     * DAO培育奖（7天）= 上周一到上周日直推持有配置的身份卡参与生态熔炼该DAO藏品的人数 / 上周一到上周日持有配置的身份卡参与生态熔炼该DAO藏品的人数 * 配置比例 * 分红池
     *
     * @param ecologyHatchDaoIncomeConf
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void daoEcologyCultivateIncome(EcologyHatchDaoIncomeConf ecologyHatchDaoIncomeConf) {
        //上周分红池
        BigDecimal bonusPool = getLastWeekBonusPool(ecologyHatchDaoIncomeConf.getDaoId(), EcologyHatchShareProfitTypeEnum.DAO_DIVIDE);
        if (!NumberUtil.isGreater(bonusPool, BigDecimal.ZERO)) {
            return;
        }


        //获取持有藏品的用户
        List<Long> holdCollectionIds = Arrays.asList(ecologyHatchDaoIncomeConf.getCollectionId());
        List<Long> userIds = userCollectionService.getUserListByCollectionIds(Arrays.asList(ecologyHatchDaoIncomeConf.getCollectionId()));
        if (CollUtil.isEmpty(userIds)) {
            return;
        }

        //需要熔炼的藏品
        List<Long> ecologyHatchcollectionIds = ecologyHatchConfDao.getEcologyHatchCollectonListByDaoId(ecologyHatchDaoIncomeConf.getDaoId());
        if (ecologyHatchcollectionIds.size() == 0) {
            return;
        }

        //统计维度
        int days = ecologyHatchDaoIncomeConf.getDimensionality().getDays();


        //获取符合前置条件的用户天数
        List<EcologyCultivateIncomeDTO> settleUsers365 = checkDAOCultivateIncome(userIds, holdCollectionIds, ecologyHatchcollectionIds, days, ecologyHatchDaoIncomeConf.getDirectThrustUserCount());

        int platformBase = settleUsers365.stream().mapToInt(o -> Objects.isNull(o.getNumberPeople()) ? 0 : o.getNumberPeople()).sum();

        if (NumberUtil.isGreater(bonusPool, BigDecimal.ZERO)
                && settleUsers365.size() > 0
                && platformBase > 0
                && NumberUtil.isGreater(ecologyHatchDaoIncomeConf.getIncomeScale().movePointLeft(2), BigDecimal.ZERO)) {
            //结算收益365
            settleDaoEcologyNodeCultivateIncome(settleUsers365, platformBase, ecologyHatchDaoIncomeConf, bonusPool, EcologyPointsEnum.DAO_CULTIVATION_AWARD, EcologyIncomeTypeEnum.DAO_CULTIVATION_AWARD, ecologyHatchDaoIncomeConf.getDaoId(), days);
        }

    }

    /**
     * 品牌权益卡-培育奖:(只算1级)
     * 前置条件:
     * 1.本人持有平台节点NFT并参与对应藏品熔炼
     * 2.推荐x人熔炼该生态藏品，直推用户取消身份限制计算公式:
     * 7天培育奖=近7天直推熔炼人数/近7天全平台推荐参与熔炼人数总和(分子总和)*配置比例*
     * 办近7天分润池
     * 30天培育奖=近30天直推熔炼人数/近30天全平台推荐参与熔炼人数总和(分子总和)*配置比例*近30天分润池
     *
     * @param ecologyHatchDaoIncomeConf
     */
    @Override
    public void daoEcologyCultivateIncomePoints(EcologyHatchDaoIncomeConf ecologyHatchDaoIncomeConf) {
        //上周分红池 积分
        BigDecimal bonusPool = getLastWeekBonusPoolNew(ecologyHatchDaoIncomeConf.getDaoId(), EcologyCollectionShareProfitTypeEnum.DAO_DIVIDE,ecologyHatchDaoIncomeConf.getHatchCollectionId());
        if (!NumberUtil.isGreater(bonusPool, BigDecimal.ZERO)) {
            return;
        }
        //获取持有权益藏品的用户
        List<Long> holdCollectionIds = Arrays.asList(ecologyHatchDaoIncomeConf.getCollectionId());
        List<Long> userIds = userCollectionService.getUserListByCollectionIds(holdCollectionIds);
        if (CollUtil.isEmpty(userIds)) {
            return;
        }
        //需要熔炼的藏品
        EcologyHatchConf ecologyHatchConf = ecologyHatchConfDao.getOneByCollectionId(ecologyHatchDaoIncomeConf.getHatchCollectionId());
        if (Objects.isNull(ecologyHatchConf)) {
            return;
        }
        //统计维度
        int days = ecologyHatchDaoIncomeConf.getDimensionality().getDays();
        //获取符合前置条件的用户天数
        List<EcologyCultivateIncomeDTO> settleUsers30 = checkDAOCultivateIncomePoints(userIds, ecologyHatchDaoIncomeConf.getHatchCollectionId(), days,ecologyHatchDaoIncomeConf.getDirectThrustUserCount());

        int platformBase = settleUsers30.stream().mapToInt(o -> Objects.isNull(o.getNumberPeople()) ? 0 : o.getNumberPeople()).sum();
        EcologyPoints ecologyPoints = ecologyPointsDao.getById(ecologyHatchConf.getEcologyPointsId());
        if (NumberUtil.isGreater(bonusPool, BigDecimal.ZERO)
                && !settleUsers30.isEmpty()
                && platformBase > 0
                && NumberUtil.isGreater(ecologyHatchDaoIncomeConf.getIncomeScale().movePointLeft(2), BigDecimal.ZERO)) {
            //结算收益30
            settleDaoEcologyNodeCultivateIncomePoints(settleUsers30, platformBase, ecologyHatchDaoIncomeConf, bonusPool,  days,ecologyPoints);
        }

    }


    /**
     * 回流dao分红池
     */
    @Override
    public void backFlowDaoPoints(EcologyHatchDaoIncomeConf ecologyHatchDaoIncomeConf){
        //上周分红池 积分
        BigDecimal bonusPool = getLastWeekBonusPoolNew(ecologyHatchDaoIncomeConf.getDaoId(), EcologyCollectionShareProfitTypeEnum.DAO_DIVIDE,ecologyHatchDaoIncomeConf.getHatchCollectionId());
        if (!NumberUtil.isGreater(bonusPool, BigDecimal.ZERO)) {
            return;
        }
        //需要熔炼的藏品
        EcologyHatchConf ecologyHatchConf = ecologyHatchConfDao.getOneByCollectionId(ecologyHatchDaoIncomeConf.getHatchCollectionId());
        if (Objects.isNull(ecologyHatchConf)) {
            return;
        }
        EcologyPoints ecologyPoints = ecologyPointsDao.getById(ecologyHatchConf.getEcologyPointsId());
        BigDecimal incomeScale = ecologyHatchDaoIncomeConf.getIncomeScaleBalance().movePointLeft(2);
        BigDecimal incomeAmount = incomeScale.multiply(bonusPool).setScale(2, BigDecimal.ROUND_DOWN);
        daoEcologyPointsWalletService.adjustAmount(ecologyHatchDaoIncomeConf.getDaoId(), ecologyPoints.getId()
                , ecologyPoints.getPointsName(), incomeAmount, DaoEcologyPointsWalletLogTypeEnum.TRANSFER_INTO_THE_DIVISION_SETTLEMENT_POOL, DaoEcologyPointsWalletLogTypeEnum.TRANSFER_INTO_THE_DIVISION_SETTLEMENT_POOL.getDescription());

    }


    /**
     * 结算DAO培育奖
     *
     * @param settleUsers
     * @param platformBase
     * @param ecologyHatchDaoIncomeConf dao收益配置
     * @param bonusPool
     */
    private void settleDaoEcologyNodeCultivateIncomePoints(List<EcologyCultivateIncomeDTO> settleUsers,
                                                           int platformBase, EcologyHatchDaoIncomeConf ecologyHatchDaoIncomeConf,
                                                           BigDecimal bonusPool,Integer days,EcologyPoints ecologyPoints) {

        for (EcologyCultivateIncomeDTO settleUser : settleUsers) {
            Long userId = settleUser.getUserId();
            //最近30天直推生态节点人数
            Integer numberPeople = settleUser.getNumberPeople();

            BigDecimal numberPeopleBigDecimal = Convert.toBigDecimal(numberPeople);
            BigDecimal platformBaseBigDecimal = Convert.toBigDecimal(platformBase);
            BigDecimal incomeScale = ecologyHatchDaoIncomeConf.getIncomeScale().movePointLeft(2);
            BigDecimal incomeAmount = numberPeopleBigDecimal.divide(platformBaseBigDecimal, 8, BigDecimal.ROUND_DOWN).multiply(incomeScale).multiply(bonusPool).setScale(2, BigDecimal.ROUND_DOWN);

            //添加积分
            if (NumberUtil.isGreater(incomeAmount, BigDecimal.ZERO)) {

                userEcologyPointsWalletService.adjustAmount(userId, ecologyPoints.getId(),ecologyPoints.getPointsName(),incomeAmount, EcologyPointsWalletEnum.DAO_CULTIVATION_AWARD,StrUtil.EMPTY);
                //用户收支表
                UserEcologyExpenditureRecord userEcologyExpenditureRecord = new UserEcologyExpenditureRecord();
                userEcologyExpenditureRecord.setUserId(userId);
                userEcologyExpenditureRecord.setDateTime(Convert.toInt(DateUtil.format(DateTime.now(), "yyyyMMdd")));
                userEcologyExpenditureRecord.setType(UserEcologyExpenditureTypeEnum.ECOLOGY_MARK);
                userEcologyExpenditureRecord.setTypeName(UserEcologyExpenditureTypeEnum.ECOLOGY_MARK.getDescription());
                userEcologyExpenditureRecord.setRemark(StrUtil.format("{} ({}天)", ecologyHatchDaoIncomeConf.getDividendIncomeName(), days));
                userEcologyExpenditureRecord.setLinkId(ecologyPoints.getId());
                userEcologyExpenditureRecord.setLinkName(UserEcologyExpenditureTypeEnum.ECOLOGY_MARK.getDescription());
                userEcologyExpenditureRecord.setLinkCount(incomeAmount);
                userEcologyExpenditureRecord.setLinkImage(StrUtil.EMPTY);
                userEcologyExpenditureRecord.insert();
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void daoPositionBonusAwardPoints(EcologyHatchDaoIncomeConf ecologyHatchDaoIncomeConf) {

        //持有权益藏品 才有资格
        Long holdCollectionId = ecologyHatchDaoIncomeConf.getCollectionId();
        if (ObjectUtil.isNull(holdCollectionId)) {
            return;
        }

        //需要熔炼的藏品
        EcologyHatchConf ecologyHatchConf = ecologyHatchConfDao.getOneByCollectionId(ecologyHatchDaoIncomeConf.getHatchCollectionId());
        if (Objects.isNull(ecologyHatchConf)) {
            return;
        }

        //上周分红池 分熔炼藏品的分红池
        BigDecimal bonusPool = getLastWeekBonusPoolNew(ecologyHatchDaoIncomeConf.getDaoId(), EcologyCollectionShareProfitTypeEnum.DAO_DIVIDE,ecologyHatchDaoIncomeConf.getHatchCollectionId());
        if (!NumberUtil.isGreater(bonusPool, BigDecimal.ZERO)) {
            return;
        }

        //持有的身份卡
        List<Long> daoIdentityCollectionIds = Arrays.asList(ecologyHatchDaoIncomeConf.getCollectionId());
        //持有的藏品
        List<Long> holdCollectionIds = Arrays.asList(ecologyHatchDaoIncomeConf.getHoldCollectionId());

        //持有藏品的用户
        List<Long> userIds = userCollectionService.getUserListByCollectionIds(daoIdentityCollectionIds);
        if (CollUtil.isEmpty(userIds)) {
            return;
        }
        EcologyPoints ecologyPoints = ecologyPointsDao.getById(ecologyHatchConf.getEcologyPointsId());


        ArrayList<UserHoldCollectionDTO> settleUser = Lists.newArrayList();
        for (Long userId : userIds) {

            //用户个人持有数量
            Integer holdCount = userCollectionService.getHoldCountByCollectionIdsAndUserId(userId, holdCollectionIds);

            //判断用户是否有进行中的记录(指定熔炼的藏品)
            Boolean underWayUser = userEcologyHatchRecordsDao.getBooleanByStatusAndUserIdAndCollectionIdsPoints(userId, ecologyHatchDaoIncomeConf.getHatchCollectionId(), UserEcologyHatchRecordsStatus.UNDER_WAY);
            if (holdCount > 0 && underWayUser) {
                UserHoldCollectionDTO userHoldCollectionDTO = new UserHoldCollectionDTO();
                userHoldCollectionDTO.setUserId(userId);
                userHoldCollectionDTO.setHoldCount(holdCount);
                settleUser.add(userHoldCollectionDTO);
            }
        }

        Integer sumHoldCount = settleUser.stream().mapToInt(o -> Objects.isNull(o.getHoldCount()) ? 0 : o.getHoldCount()).sum();
        BigDecimal incomeScale = ecologyHatchDaoIncomeConf.getIncomeScale().movePointLeft(2);
        if (sumHoldCount > 0
                && NumberUtil.isGreater(incomeScale, BigDecimal.ZERO)
                && NumberUtil.isGreater(bonusPool, BigDecimal.ZERO)) {
            //结算收益
            settleDaoEcologyNodeTakePsitionIncomePoints(settleUser, sumHoldCount, incomeScale, bonusPool, ecologyHatchDaoIncomeConf.getDividendIncomeName(), ecologyPoints);
        }

    }

    /**
     * DAO-持仓奖
     *
     * @param settleUser
     * @param sumHoldCount
     * @param incomeScale
     * @param bonusPool
     */
    private void settleDaoEcologyNodeTakePsitionIncomePoints(ArrayList<UserHoldCollectionDTO> settleUser, Integer sumHoldCount,
                                                             BigDecimal incomeScale, BigDecimal bonusPool, String incomeName,EcologyPoints ecologyPoints) {

        for (UserHoldCollectionDTO userHoldCollectionDTO : settleUser) {

            Integer holdCount = userHoldCollectionDTO.getHoldCount();
            Long userId = userHoldCollectionDTO.getUserId();

            BigDecimal incomeAmount = Convert.toBigDecimal(holdCount).divide(Convert.toBigDecimal(sumHoldCount), 8, BigDecimal.ROUND_DOWN).multiply(incomeScale).multiply(bonusPool).setScale(2, BigDecimal.ROUND_DOWN);

            //添加积分
            if (NumberUtil.isGreater(incomeAmount, BigDecimal.ZERO)) {
                //增加生态积分
                userEcologyPointsWalletService.adjustAmount(userId, ecologyPoints.getId(),ecologyPoints.getPointsName(),incomeAmount,
                        EcologyPointsWalletEnum.DAO_POSITION_BONUS_AWARD, StrUtil.EMPTY);

                //用户收支表
                UserEcologyExpenditureRecord userEcologyExpenditureRecord = new UserEcologyExpenditureRecord();
                userEcologyExpenditureRecord.setUserId(userId);
                userEcologyExpenditureRecord.setDateTime(Convert.toInt(DateUtil.format(DateTime.now(), "yyyyMMdd")));
                userEcologyExpenditureRecord.setType(UserEcologyExpenditureTypeEnum.ECOLOGY_MARK);
                userEcologyExpenditureRecord.setTypeName(UserEcologyExpenditureTypeEnum.ECOLOGY_MARK.getDescription());
                userEcologyExpenditureRecord.setRemark(incomeName);
                userEcologyExpenditureRecord.setLinkId(ecologyPoints.getId());
                userEcologyExpenditureRecord.setLinkName(UserEcologyExpenditureTypeEnum.ECOLOGY_MARK.getDescription());
                userEcologyExpenditureRecord.setLinkCount(incomeAmount);
                userEcologyExpenditureRecord.setLinkImage(StrUtil.EMPTY);
                userEcologyExpenditureRecord.insert();
            }
        }
    }


    /**
     * 培育奖
     * 前置条件：
     * 1.持有城主/节点藏品；
     * 2.城主用户当前正在参与生态熔炼（有当前正在进行中的记录）
     * <p>
     * 计算公式：
     * 1）生态培育奖（365天）=下一级是(城主或者生态节点)并且有熔炼记录在365天内的人数/最近365天内有熔炼记录并且是(城主或者生态节点)的人数*配置比例*分红池
     * 2）生态培育奖（7天）= 下一级是(城主或者生态节点)并且有熔炼记录在7天内的人数/最近7天内有熔炼记录并且是(城主或者生态节点)的人数*配置比例*分红池
     * <p>
     * 人话:
     * 1）生态培育奖（365天）=下一级是(城主或者生态节点)并且有熔炼记录在365天内的人数/最近365天内有熔炼记录并且是(城主或者生态节点)的人数*配置比例*分红池
     * 2）生态培育奖（7天）= 下一级是(城主或者生态节点)并且有熔炼记录在7天内的人数/最近7天内有熔炼记录并且是(城主或者生态节点)的人数*配置比例*分红池
     * <p>
     * bonusPool 分红池
     * collectionIds 持有藏品  节点藏品结合/城主
     * income 收益类型
     * ecologyPointsEnum 积分类型
     * day 天数 7或者365
     */
    private void settleEcologyCultivateIncome(BigDecimal bonusPool, List<Long> collectionIds, EcologyIncomeTypeEnum income, EcologyPointsEnum ecologyPointsEnum) {
        //获取持有藏品的用户
        List<Long> userIds = userCollectionService.getUserListByCollectionIds(collectionIds);
        if (CollUtil.isEmpty(userIds)) {
            return;
        }


        //获取符合前置条件的用户天数
        List<EcologyCultivateIncomeDTO> settleUsers = checkCultivateIncome(userIds, collectionIds, income.getDay());

        //符合条件的人数总和
        int platformBase = settleUsers.stream().mapToInt(o -> Objects.isNull(o.getNumberPeople()) ? 0 : o.getNumberPeople()).sum();

        //收益配置
        EcologyHatchIncomeConf incomeConf = ecologyHatchIncomeConfDao.getOneByType(income);

        if (NumberUtil.isGreater(bonusPool, BigDecimal.ZERO)
                && settleUsers.size() > 0
                && platformBase > 0
                && NumberUtil.isGreater(incomeConf.getIncomeScale().movePointLeft(2), BigDecimal.ZERO)) {
            //结算收益365
            settleEcologyNodeCultivateIncome(settleUsers, platformBase, incomeConf, bonusPool, ecologyPointsEnum, income);
        }
    }

    /**
     * DAO贡献奖积分
     * 前置条件：
     * 1.持有配置的身份卡藏品；
     * 2.用户当前正在参与生态熔炼（有当前正在进行中的记录）
     * 3.直推至少X个持有配置的身份卡，且X个用户都参与生态熔炼（有当前正在进行中的记录，X取直推人数配置）
     * <p>
     * 计算公式：
     * 1）DAO贡献奖（365天）= 最近365天团队内生态熔炼该DAO藏品的生态燃料（扣除最大直推团队投入） / 最近365天全平台熔炼该DAO藏品的生态燃料 * 配置比例 * 分红池
     * 1）DAO贡献奖（7天）= 上周一到上周日团队内生态熔炼该DAO藏品的生态燃料（扣除最大直推团队投入） / 上周一到上周日全平台熔炼该DAO藏品的生态燃料 * 配置比例 * 分红池
     *
     * 品牌权益卡-贡献奖:(只算1级)
     * 前置条件:
     * 1、本人持有平台节点NFT并参与对应藏品熔炼
     * 2、直推3人参与熔炼，直推用户取消身份限制。
     * 计算公式:
     * 7天贡献奖=近7天直推熔炼总组数/近7天全平台推荐熔炼总组数(分子总和)*配置比例*近7天分润池
     * 30天贡献奖=近30天直推熔炼总组数/近30天全平台推荐熔炼总组数(分子总和)*配置比例*近30天分润池
     *
     * @param ecologyHatchDaoIncomeConf
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void daoEcologyContributionIncomePoints(EcologyHatchDaoIncomeConf ecologyHatchDaoIncomeConf) {
        //上周分红池
        BigDecimal bonusPool = getLastWeekBonusPoolNew(ecologyHatchDaoIncomeConf.getDaoId(), EcologyCollectionShareProfitTypeEnum.DAO_DIVIDE,ecologyHatchDaoIncomeConf.getHatchCollectionId());
        if (!NumberUtil.isGreater(bonusPool, BigDecimal.ZERO)) {
            return;
        }

        //获取持有藏品的用户
        List<Long> holdCollectionIds = Arrays.asList(ecologyHatchDaoIncomeConf.getCollectionId());
        List<Long> userIds = userCollectionService.getUserListByCollectionIds(holdCollectionIds);
        if (CollUtil.isEmpty(userIds)) {
            return;
        }
        //需要熔炼的藏品
        EcologyHatchConf ecologyHatchConf = ecologyHatchConfDao.getOneByCollectionId(ecologyHatchDaoIncomeConf.getHatchCollectionId());
        if (Objects.isNull(ecologyHatchConf)) {
            return;
        }
//        List<Long> ecologyHatchCollectionIds = Arrays.asList(ecologyHatchDaoIncomeConf.getHatchCollectionId());

        List<Long> settleUser = checkDaoEcologyNodeContributionIncomePoints(userIds, ecologyHatchDaoIncomeConf.getHatchCollectionId(), ecologyHatchDaoIncomeConf.getDirectThrustUserCount());
        if (CollUtil.isEmpty(settleUser)) {
            return;
        }

        BigDecimal incomeScale = ecologyHatchDaoIncomeConf.getIncomeScale().movePointLeft(2);
        //统计维度
        int days = ecologyHatchDaoIncomeConf.getDimensionality().getDays();
        EcologyPoints ecologyPoints = ecologyPointsDao.getById(ecologyHatchConf.getEcologyPointsId());

        ArrayList<EcologyHatchEffectiveTeamTokenDTO> settleList = Lists.newArrayList();
        BigDecimal platformSum = BigDecimal.ZERO;
        for (Long userId : settleUser) {
            EcologyHatchEffectiveTeamTokenDTO effectiveTeamTokendto = getDaoEffectiveTeamTokenNew(userId, ecologyHatchDaoIncomeConf.getHatchCollectionId(), days);
            if (NumberUtil.isGreater(effectiveTeamTokendto.getTeamToken365(), BigDecimal.ZERO)) {
                platformSum = platformSum.add(effectiveTeamTokendto.getTeamToken365());
                settleList.add(effectiveTeamTokendto);
            }
        }

        for (EcologyHatchEffectiveTeamTokenDTO ecologyHatchEffectiveTeamTokenDTO : settleList) {
            BigDecimal teamToken = ecologyHatchEffectiveTeamTokenDTO.getTeamToken365();
            if (NumberUtil.isGreater(teamToken, BigDecimal.ZERO)
                    && NumberUtil.isGreater(platformSum, BigDecimal.ZERO)
                    && NumberUtil.isGreater(bonusPool, BigDecimal.ZERO)) {
                addDaoecologyNodeContributionIncomePoints(teamToken, platformSum, incomeScale, bonusPool, ecologyHatchEffectiveTeamTokenDTO.getUserId(), ecologyHatchDaoIncomeConf,ecologyPoints);
            }
        }
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void communityNetworkEcologicalCultivationAward() {
//        1.成为社区网点；
//        2.网点负责人当前正在参与生态熔炼（有当前正在进行中的记录）
        // 获取所有社区网点并且参与熔炼的数据id.
        // 最近7天全平台参与.
//        BigDecimal platformSum7 = userEcologyHatchRecordsDao.getBonusPool(7);
        //上周平台分红池
        BigDecimal platformSum7 = getLastWeekBonusPool(DaoInfoEnum.META_DAO.getId(), EcologyHatchShareProfitTypeEnum.PLATFORM_DIVIDE);

        List<Long> workRoomParticipateInSmeltingUserId = communityNetworkAndParticipateInSmelting();
        EcologyHatchIncomeConf contributionAward365 = ecologyHatchIncomeConfDao.getOneByType(EcologyIncomeTypeEnum.COMMUNITY_ECOLOGICAL_CONTRIBUTION_AWARD_365);
        EcologyHatchIncomeConf contributionAward7 = ecologyHatchIncomeConfDao.getOneByType(EcologyIncomeTypeEnum.COMMUNITY_ECOLOGICAL_CONTRIBUTION_AWARD_7);
        // 365天的分红比例
        BigDecimal incomeScale365 = contributionAward365.getIncomeScale().movePointLeft(2);
        // 7天的分红比例
        BigDecimal incomeScale7 = contributionAward7.getIncomeScale().movePointLeft(2);

        //初始化平台总业绩
        BigDecimal teamHoldToke365 = BigDecimal.ZERO;
        BigDecimal teamHoldToke7 = BigDecimal.ZERO;

        // 循环处理这批数据,排除下级.
//        for (Long workRoomId : workRoomParticipateInSmeltingUserId) {
//            // 定义一个list,获取当前排除自己的ID
//            List<Long> excludeId = workRoomParticipateInSmeltingUserId.stream().filter(workRoomIds -> workRoomIds.longValue() != workRoomId.longValue()).collect(Collectors.toList());
//            if (CollUtil.isEmpty(excludeId)) {
//                excludeId.add(0L);
//            }
//            // 获取当前社区网点下10级,获取10级后,获取
//            List<Long> afterExclusionUserId = userRelevanceDao.excludeSubordinateCommunity(workRoomId, excludeId);
//            if (CollUtil.isEmpty(afterExclusionUserId)) {
//                continue;
//            }
//            // 团队365天的业绩
//            BigDecimal sumPrice365 = userEcologyHatchRecordsDao.getSumPriceByUserIdListAndDay(afterExclusionUserId,365);
//            BigDecimal sumPrice7 = userEcologyHatchRecordsDao.getSumPriceByUserIdListAndLastWeek(afterExclusionUserId);
//
//        }

        // 计算所有团队业绩的总的分红池,拿到以后循环处理,需要获取一次社区网点的排除后的当前团队的业绩数据
        for (Long shareOutBonus : workRoomParticipateInSmeltingUserId) {
            // 定义一个list,获取当前排除自己的ID
            List<Long> excludeId = workRoomParticipateInSmeltingUserId.stream().filter(workRoomIds -> workRoomIds.longValue() != shareOutBonus.longValue()).collect(Collectors.toList());
            // 排除对应id以及旗下数据,根据排除的id,只向下级查找
            if (CollUtil.isEmpty(excludeId)) {
                excludeId.add(0L);
            }
            // 获取当前用户城市服务中心的id
            List<Long> excludesTheCityServiceCenterOfTheCurrentUser = userRelevanceDao.excludesTheCityServiceCenterOfTheCurrentUser(shareOutBonus);
            // 获取当前社区网点下10级,获取10级后,获取
            List<Long> afterExclusionUserId = userRelevanceDao.excludeSubordinateCommunity(shareOutBonus, excludeId, excludesTheCityServiceCenterOfTheCurrentUser);
            if (CollUtil.isEmpty(afterExclusionUserId)) {
                continue;
            }
            // 团队365天的业绩
            BigDecimal sumPrice365 = userEcologyHatchRecordsDao.getSumPriceByUserIdListAndDay(afterExclusionUserId, 365);
            // 团队7天业绩
            BigDecimal sumPrice7 = userEcologyHatchRecordsDao.getSumPriceByUserIdListAndLastWeek(afterExclusionUserId);
            teamHoldToke365 = teamHoldToke365.add(sumPrice365);
            teamHoldToke7 = teamHoldToke7.add(sumPrice7);
        }

        for (Long shareOutBonus : workRoomParticipateInSmeltingUserId) {
            // 定义一个list,获取当前排除自己的ID
            List<Long> excludeId = workRoomParticipateInSmeltingUserId.stream().filter(workRoomIds -> workRoomIds.longValue() != shareOutBonus.longValue()).collect(Collectors.toList());
            // 排除对应id以及旗下数据,根据排除的id,只向下级查找
            if (CollUtil.isEmpty(excludeId)) {
                excludeId.add(0L);
            }
            List<Long> excludesTheCityServiceCenterOfTheCurrentUser = userRelevanceDao.excludesTheCityServiceCenterOfTheCurrentUser(shareOutBonus);
            // 获取当前社区网点下10级,获取10级后,获取
            List<Long> afterExclusionUserId = userRelevanceDao.excludeSubordinateCommunity(shareOutBonus, excludeId, excludesTheCityServiceCenterOfTheCurrentUser);
            if (CollUtil.isEmpty(afterExclusionUserId)) {
                continue;
            }
            // 团队365天的业绩
            BigDecimal sumPrice365 = userEcologyHatchRecordsDao.getSumPriceByUserIdListAndDay(afterExclusionUserId, 365);
            // 团队7天业绩
            BigDecimal sumPrice7 = userEcologyHatchRecordsDao.getSumPriceByUserIdListAndLastWeek(afterExclusionUserId);
            if (teamHoldToke365.compareTo(BigDecimal.ZERO) == 1) {
                addecologyNodeContributionIncome(sumPrice365, teamHoldToke365, incomeScale365, platformSum7, shareOutBonus, EcologyIncomeTypeEnum.COMMUNITY_ECOLOGICAL_CONTRIBUTION_AWARD_365, EcologyPointsEnum.CONTRIBUTION_AWARD_365);
            }
            if (teamHoldToke7.compareTo(BigDecimal.ZERO) == 1) {
                addecologyNodeContributionIncome(sumPrice7, teamHoldToke7, incomeScale7, platformSum7, shareOutBonus, EcologyIncomeTypeEnum.COMMUNITY_ECOLOGICAL_CONTRIBUTION_AWARD_7, EcologyPointsEnum.CONTRIBUTION_AWARD_365);

            }
        }

    }


    @Override
    public void ecologicalCultivationOfUrbanServiceCenter() {

//        1.成为城市服务中心；
//
//        2.城市服务中心负责人当前正在参与生态熔炼（有当前正在进行中的记录）
        EcologyHatchIncomeConf contributionAward365 = ecologyHatchIncomeConfDao.getOneByType(EcologyIncomeTypeEnum.CITY_CULTIVATION_AWARD_365);
        EcologyHatchIncomeConf contributionAward7 = ecologyHatchIncomeConfDao.getOneByType(EcologyIncomeTypeEnum.CITY_CULTIVATION_AWARD_7);
        // 参与熔炼的城市服务中心id
        List<Long> participationSmeltUserIds365 = participationSmeltUrbanServiceCenter(365,null);

        if (CollUtil.isEmpty(participationSmeltUserIds365)) {
            log.info("城市服务中心365天培育奖发放失败.失败原因,参与熔炼城市服务中心id为空");
        }
        List<EcologyCultivateIncomeDTO> cityServiceCenterRecommendations = getCityServiceCenterRecommendations(participationSmeltUserIds365);
        // 有效的城市服务中心
        List<EcologyCultivateIncomeDTO> cityServiceCenterRecommendationsStream = cityServiceCenterRecommendations.stream().filter(ecologyCultivateIncomeDTO -> !ecologyCultivateIncomeDTO.getNumberPeople().equals(0)).collect(Collectors.toList());
//        BigDecimal bonusPool = userEcologyHatchRecordsDao.getBonusPool(7);
        int sum365 = cityServiceCenterRecommendationsStream.stream().mapToInt(EcologyCultivateIncomeDTO::getNumberPeople).sum();
        //上周平台分红池
        BigDecimal bonusPool = getLastWeekBonusPool(DaoInfoEnum.META_DAO.getId(), EcologyHatchShareProfitTypeEnum.PLATFORM_DIVIDE);
        // 365天奖励发放奖励.
        settleEcologyNodeCultivateIncome(cityServiceCenterRecommendationsStream, sum365, contributionAward365, bonusPool, EcologyPointsEnum.city_CULTIVATION_AWARD_365, EcologyIncomeTypeEnum.CITY_CULTIVATION_AWARD_365);
        // 参与熔炼的城市服务中心id
        List<Long> participationSmeltUserIds7 = participationSmeltUrbanServiceCenter(7,null);
        if (CollUtil.isEmpty(participationSmeltUserIds7)) {
            log.info("城市服务中心7天培育奖发放失败.失败原因,参与熔炼城市服务中心id为空");
        }
        List<EcologyCultivateIncomeDTO> cityServiceCenterRecommendations7 = getCityServiceCenterRecommendations(participationSmeltUserIds7);
        // 有效的城市服务中心
        List<EcologyCultivateIncomeDTO> cityServiceCenterRecommendationsStream7 = cityServiceCenterRecommendations7.stream().filter(ecologyCultivateIncomeDTO -> !ecologyCultivateIncomeDTO.getNumberPeople().equals(0)).collect(Collectors.toList());
//        BigDecimal bonusPool7 = userEcologyHatchRecordsDao.getBonusPool(7);
//        BigDecimal bonusPool7 = ecologyHatchShareProfitDao.getLastWeekBonusPool(DaoInfoEnum.META_DAO.getId(), EcologyHatchShareProfitTypeEnum.PLATFORM_DIVIDE);
        int sum7 = cityServiceCenterRecommendationsStream7.stream().mapToInt(EcologyCultivateIncomeDTO::getNumberPeople).sum();
        // 7天奖励发放奖励.
        settleEcologyNodeCultivateIncome(cityServiceCenterRecommendationsStream7, sum7, contributionAward7, bonusPool, EcologyPointsEnum.city_CULTIVATION_AWARD_7, EcologyIncomeTypeEnum.CITY_CULTIVATION_AWARD_7);
    }

    @Override
    public void urbanServiceCenterEcologicalContribution() {
//        1.成为城市服务中心；
//        2.城市服务中心负责人当前正在参与生态熔炼（有当前正在进行中的记录）
//        1）城市生态贡献奖（365天）=最近365天团队生态熔炼中投入的生态燃料（排除平级团队）/最近365天全平台所有城市服务中心投入生态熔炼的生态燃料*配置比例*分红池
//        2）城市生态贡献奖（7天）=最近7天团队生态熔炼中投入的生态燃料（排除平级团队）/最近7天全平台所有城市服务中心投入生态熔炼的生态燃料*配置比例*分红池
        EcologyHatchIncomeConf contributionAward365 = ecologyHatchIncomeConfDao.getOneByType(EcologyIncomeTypeEnum.CITY_CONTRIBUTION_AWARD_365);
        EcologyHatchIncomeConf contributionAward7 = ecologyHatchIncomeConfDao.getOneByType(EcologyIncomeTypeEnum.CITY_CONTRIBUTION_AWARD_7);
//        BigDecimal platformSum7 = userEcologyHatchRecordsDao.getBonusPool(7);
        BigDecimal platformSum7 = getLastWeekBonusPool(DaoInfoEnum.META_DAO.getId(), EcologyHatchShareProfitTypeEnum.PLATFORM_DIVIDE);
        theCityServiceCenterGivesOutIncentives(365, contributionAward365, platformSum7, EcologyIncomeTypeEnum.CITY_CONTRIBUTION_AWARD_365, EcologyPointsEnum.city_CONTRIBUTION_AWARD_365);
        theCityServiceCenterGivesOutIncentives(7, contributionAward7, platformSum7, EcologyIncomeTypeEnum.CITY_CONTRIBUTION_AWARD_7, EcologyPointsEnum.city_CONTRIBUTION_AWARD_7);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void ecologyDaoRelease(EcologyHatchShareProfit ecologyHatchShareProfit) {
        //金额小于0 跳出
        if (NumberUtil.isGreaterOrEqual(BigDecimal.ZERO, ecologyHatchShareProfit.getDaoDivideIntoPoints())) {
            Assert.isTrue(ecologyHatchShareProfitDao.updateSettleStatusById(ecologyHatchShareProfit.getId(), EcologyHatchShareProfitStatus.PROCESSING_SUCCESS), () -> new GlobalRunTimeException("修改失败"));
            return;
        }
        daoEcologyPointsService.addAmountAndSubFrozenAmount(ecologyHatchShareProfit.getDaoId(), ecologyHatchShareProfit.getDaoDivideIntoPoints(), DaoEcologyPointsDetailRecordsTypeEnum.RELEASE_TO_AVAILABLE);
        Assert.isTrue(ecologyHatchShareProfitDao.updateSettleStatusById(ecologyHatchShareProfit.getId(), EcologyHatchShareProfitStatus.PROCESSING_SUCCESS), () -> new GlobalRunTimeException("修改失败"));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void ecologyBonusPoolFlowInto(Long daoId) {

        if (daoId == DaoInfoEnum.META_DAO.getId()) {
            //获取上周的平台的分红池
            BigDecimal bonusPool = getLastWeekBonusPool(DaoInfoEnum.META_DAO.getId(), EcologyHatchShareProfitTypeEnum.PLATFORM_DIVIDE);
            //获取平台当天的收益
            BigDecimal platformIncome = ecologyHatchIncomeConfDao.getSumAmountIncomeByDaoIdAndTypes(DaoInfoEnum.META_DAO.getId(), EcologyIncomeTypeEnum.getplatformIncomeList());
            if (NumberUtil.isGreater(bonusPool, platformIncome)) {
                BigDecimal bigDecimal = bonusPool.subtract(platformIncome).setScale(2, BigDecimal.ROUND_DOWN);
                if (NumberUtil.isGreater(bigDecimal, BigDecimal.ZERO)) {
                    //平台收益流入
                    daoEcologyPointsService.addAmount(DaoInfoEnum.META_DAO.getId(), bigDecimal, DaoEcologyPointsDetailRecordsTypeEnum.DIVIDE_POOL_SURPLUS_TRANSFER_IN, DaoEcologyPointsDetailRecordsTypeEnum.DIVIDE_POOL_SURPLUS_TRANSFER_IN.getDescription());
                }
            }
        }

        //获取上周的平台的分红池
        BigDecimal lastWeekBonusPool = getLastWeekBonusPool(daoId, EcologyHatchShareProfitTypeEnum.DAO_DIVIDE);
        //获取DAO当天的收益
        BigDecimal daoIncome = ecologyHatchIncomeConfDao.getSumAmountIncomeByDaoIdAndTypes(daoId, EcologyIncomeTypeEnum.getDaoIncomeList());

        if (NumberUtil.isGreater(lastWeekBonusPool, daoIncome)) {
            BigDecimal bigDecimal = lastWeekBonusPool.subtract(daoIncome).setScale(2, BigDecimal.ROUND_DOWN);

            if (NumberUtil.isGreater(bigDecimal, BigDecimal.ZERO)) {
                //DAO收益流入
                daoEcologyPointsService.addAmount(daoId, bigDecimal, DaoEcologyPointsDetailRecordsTypeEnum.DIVIDE_POOL_SURPLUS_TRANSFER_IN, DaoEcologyPointsDetailRecordsTypeEnum.DIVIDE_POOL_SURPLUS_TRANSFER_IN.getDescription());
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void ecologyStatisticalProportion(EcologyHatchCollecionShareProfitConf ecologyHatchCollecionShareProfitConf) {
        Long collectionId = ecologyHatchCollecionShareProfitConf.getCollectionId();
        //主理人
        UserCreatorInfo dao = userCreatorInfoDao.getById(ecologyHatchCollecionShareProfitConf.getDaoId());
        if (ObjectUtil.isNull(dao)) {
            return;
        }

        BigDecimal platformDivideScale = BigDecimal.ZERO;
        BigDecimal daoDivideIntoScale = BigDecimal.ZERO;
        EcologyHatchShareProfitMethodConf ecologyHatchShareProfitMethodConf = ecologyHatchShareProfitMethodConfDao.getOneByEcologyHatchId(ecologyHatchCollecionShareProfitConf.getConfId());
        Long resonanceServiceCenterDaoUserId = null;
        Date daoOnlineTime = null;
        if (Objects.nonNull(ecologyHatchShareProfitMethodConf)) {
            UserCreatorInfo resonanceServiceCenterDao = userCreatorInfoDao.getById(ecologyHatchShareProfitMethodConf.getResonanceServiceCenterDaoId());
            if (Objects.nonNull(resonanceServiceCenterDao)) {
                resonanceServiceCenterDaoUserId = resonanceServiceCenterDao.getUserId();
                daoOnlineTime = resonanceServiceCenterDao.getOnlineTime();
            }
        }
        //查询主理人下的所有熔炼金额汇总
        BigDecimal daoSumPrice = userEcologyHatchRecordsDao.getSumPriceByUserIdAndCollectionIdAndTime(dao.getUserId(), collectionId, DateUtil.beginOfDay(DateTime.now()), resonanceServiceCenterDaoUserId, daoOnlineTime);
        //平台熔炼数值
        BigDecimal sumPrice = userEcologyHatchRecordsDao.getSumPriceByUserIdAndCollectionIdAndTime(null, collectionId, DateUtil.beginOfDay(DateTime.now()), null, null);
        //如果平台和DAO都没有熔炼 则不修改
        if (NumberUtil.isGreaterOrEqual(BigDecimal.ZERO, sumPrice) && NumberUtil.isGreaterOrEqual(BigDecimal.ZERO, daoSumPrice)) {
            return;
        }

        //如果主理人所有下级熔炼的金额为0 则平台占比100%  DAO占比0%
        if (NumberUtil.isGreaterOrEqual(BigDecimal.ZERO, daoSumPrice)) {
            platformDivideScale = Convert.toBigDecimal(100);
        } else if (NumberUtil.isGreaterOrEqual(BigDecimal.ZERO, sumPrice)) {//如果平台熔炼为0 则平台占比0%  DAO占比100%
            daoDivideIntoScale = Convert.toBigDecimal(100);
        } else {
            //DAO熔炼金额除以平台熔炼总金额 = DAO占比
            daoDivideIntoScale = daoSumPrice.divide(sumPrice, 8, BigDecimal.ROUND_DOWN).multiply(Convert.toBigDecimal(100)).setScale(2, BigDecimal.ROUND_DOWN);
            platformDivideScale = Convert.toBigDecimal(100).subtract(daoDivideIntoScale);
        }

        EcologyHatchDivideIntoLog ecologyHatchDivideIntoLog = new EcologyHatchDivideIntoLog();
        ecologyHatchDivideIntoLog.setCollectionId(ecologyHatchCollecionShareProfitConf.getCollectionId());

        DigitalCollection collection = digitalCollectionDao.getById(ecologyHatchCollecionShareProfitConf.getCollectionId());
        ecologyHatchDivideIntoLog.setCollectionName(collection.getFirstTitle());
        ecologyHatchDivideIntoLog.setPlatformUsePoints(sumPrice);
        ecologyHatchDivideIntoLog.setDaoUsePoints(daoSumPrice);
        ecologyHatchDivideIntoLog.setPlatformDivideIntoScale(platformDivideScale);
        ecologyHatchDivideIntoLog.setDaoDivideIntoScale(daoDivideIntoScale);
        ecologyHatchDivideIntoLog.insert();

        Assert.isTrue(ecologyHatchCollecionShareProfitConfDao.updateDivideScaleByCollectionIdAndType(ecologyHatchCollecionShareProfitConf.getCollectionId(), platformDivideScale, daoDivideIntoScale), () -> new GlobalRunTimeException("修改失败"));
    }

    /**
     * 结算规则： 设最大值X，
     * 1. 第1个月该DAO结算金额为A，X = A，第1个月不进行结算；
     * 2. 第2个月该DAO结算金额为B，
     * 若B ≥ A，则X = B，结算金额为A；
     * 若B＜A，则X = A，结算金额为B；
     * 3. 第3个月开始按照第2个月结算方式以此类推。
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void ecologyReleaseMarketValueManagement(MarketManagementDaoPool marketManagementDaoPool) {
        MarketManagementDaoPool lockPool = marketManagementDaoPoolDao.getLockPool(marketManagementDaoPool.getEcologyHatchId(), marketManagementDaoPool.getCollectionId(), marketManagementDaoPool.getDaoId(), marketManagementDaoPool.getId(), marketManagementDaoPool.getStartTime());
        if (Objects.nonNull(lockPool)) {//有历史数据
            //如果新数据大于等于历史数据 则新数据为最大值
            if (NumberUtil.isGreater(marketManagementDaoPool.getAmount(), lockPool.getAmount())) {
                marketManagementDaoPoolDao.updateIsSettleById(lockPool.getId(), Boolean.TRUE);
                DigitalCollection digitalCollection = digitalCollectionDao.getById(lockPool.getCollectionId());
                //加钱
                daoEcologyPointsService.addAmount(lockPool.getDaoId(), lockPool.getAmount(), DaoEcologyPointsDetailRecordsTypeEnum.MARKET_VALUE_MANAGEMENT_TRANSFER_IN, digitalCollection.getFirstTitle());
            } else {
                //则历史数据为最大值
                // 结算
                marketManagementDaoPoolDao.updateIsSettleById(marketManagementDaoPool.getId(), Boolean.TRUE);
                DigitalCollection digitalCollection = digitalCollectionDao.getById(marketManagementDaoPool.getCollectionId());
                //加钱
                daoEcologyPointsService.addAmount(marketManagementDaoPool.getDaoId(), marketManagementDaoPool.getAmount(), DaoEcologyPointsDetailRecordsTypeEnum.MARKET_VALUE_MANAGEMENT_TRANSFER_IN, digitalCollection.getFirstTitle());
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void managementThaw() {
        Date now = new Date();
        // 获取所有冻结的生态市值管理分成记录
        List<EcologyHatchShareProfit> frozenList = ecologyHatchShareProfitDao.getFrozenList();
        if (CollectionUtils.isEmpty(frozenList)) {
            return;
        }
        // 获取对应的所有熔炼记录Id
        Map<Long, List<EcologyHatchShareProfit>> frozenMap = frozenList.stream().collect(Collectors.groupingBy(EcologyHatchShareProfit::getUserRecordId));
        List<Long> userRecordIdList = frozenMap.keySet().stream().collect(Collectors.toList());
        List<UserEcologyHatchRecords> userEcologyHatchRecordsList = userEcologyHatchRecordsDao.getListByIds(userRecordIdList);
        // 获取熔炼记录归属的DaoId对应的熔炼记录
        Map<Long, List<UserEcologyHatchRecords>> userEcologyHatchRecordsUserInDaoMap = userEcologyHatchRecordsList.stream().collect(Collectors.groupingBy(UserEcologyHatchRecords::getUserInDaoId));
        for (Long daoId : userEcologyHatchRecordsUserInDaoMap.keySet()) {
            // 通过藏品ID再区分
            List<UserEcologyHatchRecords> userEcologyHatchRecords = userEcologyHatchRecordsUserInDaoMap.get(daoId);
            // 藏品ID对应
            Map<Long, List<UserEcologyHatchRecords>> ecologyHatchShareProfitGroupCollectionIdMap = userEcologyHatchRecords.stream().collect(Collectors.groupingBy(UserEcologyHatchRecords::getCollectionId));
            // 遍历 判断不同藏品下dao的拉新人数是否符合
            for (Long collectionId : ecologyHatchShareProfitGroupCollectionIdMap.keySet()) {
                // 获取熔炼配置ID
                EcologyHatchConf ecologyHatchConf = ecologyHatchConfDao.getOneByCollectionId(collectionId);
                if (Objects.isNull(ecologyHatchConf)) {
                    continue;
                }
                // 获取对应的分润方法配置
                EcologyHatchShareProfitMethodConf ecologyHatchShareProfitMethodConf = ecologyHatchShareProfitMethodConfDao.getOneByEcologyHatchId(ecologyHatchConf.getId());
                if (Objects.isNull(ecologyHatchShareProfitMethodConf)) {
                    continue;
                }
                EcologyHatchCollecionShareProfitConf ecologyHatchCollecionShareProfitConf = ecologyHatchCollecionShareProfitConfDao.getOneByCollectionIdAndType(collectionId, EcologyHatchShareProfitTypeEnum.MARKET_VALUE_MANAGEMENT);
                if (Objects.nonNull(ecologyHatchShareProfitMethodConf.getResonanceDaoId()) && ecologyHatchShareProfitMethodConf.getResonanceDaoId().equals(daoId)) {
                    // 该藏品下的品牌方
                    UserCreatorInfo dao = userCreatorInfoDao.getById(ecologyHatchShareProfitMethodConf.getResonanceDaoId());
                    // 品牌方拉新人数
                    Integer daoNewUserNum = userInfoDao.getDaoNewUserNum(dao.getUserId(), dao.getOnlineTime());
                    if (ecologyHatchCollecionShareProfitConf.getDaoNewUserNum() <= daoNewUserNum) {
                        // 解冻
                        List<EcologyHatchShareProfit> needList = new ArrayList<>();
                        // 获取熔炼记录对应的分成记录
                        List<UserEcologyHatchRecords> userEcologyHatchRecordsCanThawList = ecologyHatchShareProfitGroupCollectionIdMap.get(collectionId);
                        for (UserEcologyHatchRecords ecologyHatchRecords : userEcologyHatchRecordsCanThawList) {
                            List<EcologyHatchShareProfit> ecologyHatchShareProfits = frozenMap.get(ecologyHatchRecords.getId());
                            needList.addAll(ecologyHatchShareProfits);
                        }
                        BigDecimal total = needList.stream().map(EcologyHatchShareProfit::getDaoDivideIntoPoints).reduce(BigDecimal.ZERO, BigDecimal::add);
                        // 减少
                        Assert.isTrue(daoEcologyPointsService.subFrozenAmountByDaoId(daoId, total,
                                DaoEcologyPointsDetailAmountTypeEnum.RELEASE_DAO, DaoEcologyPointsDetailRecordsTypeEnum.FREEZE_TO_MARKET_CAP_MANAGEMENT_POOL, DateTime.of(now)), () -> new GlobalRunTimeException("减少待释放燃料(品牌方老用户)失败"));
                        // 添加市值管理池子中金额
                        Long pool = marketManagementDaoPoolService.addAmount(ecologyHatchConf.getId(), collectionId, daoId, total, now);
                        List<Long> ecologyHatchShareProfitIds = needList.stream().map(EcologyHatchShareProfit::getId).collect(Collectors.toList());
                        Assert.isTrue(ecologyHatchShareProfitDao.updatePoolIdById(ecologyHatchShareProfitIds, pool), () -> new GlobalRunTimeException("流入市值池失败"));
                    }
                } else if (Objects.nonNull(ecologyHatchShareProfitMethodConf.getResonanceServiceCenterDaoId()) && ecologyHatchShareProfitMethodConf.getResonanceServiceCenterDaoId().equals(daoId)) {
                    // 共振方
                    UserCreatorInfo dao = userCreatorInfoDao.getById(ecologyHatchShareProfitMethodConf.getResonanceDaoId());
                    UserCreatorInfo serviceCenterDao = userCreatorInfoDao.getById(daoId);
                    // 共振方拉新人数
                    Integer serviceCenterNewUserNum = userInfoDao.getServiceCenterNewUserNum(serviceCenterDao.getUserId(), dao.getUserId(), serviceCenterDao.getOnlineTime());
                    Integer needServiceCenterNewUserNum = BigDecimalUtils.divide(ecologyHatchCollecionShareProfitConf.getServiceCenterNewUserNum(), ecologyHatchShareProfitMethodConf.getResonanceServiceCenterCoefficient().movePointLeft(2), 0, RoundingMode.DOWN).intValue();
                    if (needServiceCenterNewUserNum <= serviceCenterNewUserNum) {
                        // 解冻
                        List<EcologyHatchShareProfit> needList = new ArrayList<>();
                        // 获取熔炼记录对应的分成记录
                        List<UserEcologyHatchRecords> userEcologyHatchRecordsCanThawList = ecologyHatchShareProfitGroupCollectionIdMap.get(collectionId);
                        for (UserEcologyHatchRecords ecologyHatchRecords : userEcologyHatchRecordsCanThawList) {
                            List<EcologyHatchShareProfit> ecologyHatchShareProfits = frozenMap.get(ecologyHatchRecords.getId());
                            needList.addAll(ecologyHatchShareProfits);
                        }
                        // 共振方需要分给自己合品牌
                        Map<Long, List<EcologyHatchShareProfit>> needMap = needList.stream().collect(Collectors.groupingBy(EcologyHatchShareProfit::getDaoId));
                        for (Long daoKey : needMap.keySet()) {
                            List<EcologyHatchShareProfit> ecologyHatchShareProfits = needMap.get(daoKey);
                            BigDecimal total = ecologyHatchShareProfits.stream().map(EcologyHatchShareProfit::getDaoDivideIntoPoints).reduce(BigDecimal.ZERO, BigDecimal::add);
                            // 减少
                            Assert.isTrue(daoEcologyPointsService.subFrozenAmountByDaoId(daoKey, total,
                                    DaoEcologyPointsDetailAmountTypeEnum.RELEASE_RESONANCE_SERVICE_CENTER, DaoEcologyPointsDetailRecordsTypeEnum.FREEZE_TO_MARKET_CAP_MANAGEMENT_POOL, DateTime.of(now)), () -> new GlobalRunTimeException("减少待释放燃料(共振服务中心老用户)失败"));
                            // 添加市值管理池子中金额
                            Long pool = marketManagementDaoPoolService.addAmount(ecologyHatchConf.getId(), collectionId, daoKey, total, now);
                            List<Long> ecologyHatchShareProfitIds = ecologyHatchShareProfits.stream().map(EcologyHatchShareProfit::getId).collect(Collectors.toList());
                            Assert.isTrue(ecologyHatchShareProfitDao.updatePoolIdById(ecologyHatchShareProfitIds, pool), () -> new GlobalRunTimeException("流入市值池失败"));
                        }
                    }
                }
            }
        }
    }


    /**
     * 生态节点-持仓奖：（只算1级）
     * <p>
     * 前置条件：
     * 品牌根据身份权益卡自定义配置
     * 计算公式：
     * 生态节点持仓奖励=用户持有生态节点藏品数量 / 全平台符合条件的生态节点藏品数量的总和(所有分子相加) * 配置比例 * 分润池
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void ecologyNodeTakePositionIncome() {
        //获取生态接点藏品
        //首先查询开着的配置
        List<EcologyHatchIncomeConfRelevance> relevanceList = ecologyHatchIncomeConfRelevanceDao.getOpen();
        if (CollectionUtils.isEmpty(relevanceList)) {
            return;
        }
        List<Long> hatchCollectionIdList = relevanceList.stream().map(EcologyHatchIncomeConfRelevance::getHatchCollectionId).distinct().collect(Collectors.toList());
        //熔炼查询积分
        List<EcologyHatchConf> ecologyHatchConfList = ecologyHatchConfDao.ListByCollectionId(hatchCollectionIdList);
        if (CollectionUtils.isEmpty(ecologyHatchConfList)) {
            return;
        }
        Map<Long, Long> ecologyHatchPointsMap = ecologyHatchConfList.stream().collect(Collectors.toMap(EcologyHatchConf::getCollectionId, EcologyHatchConf::getEcologyPointsId));
        List<Long> pointsList = new ArrayList<>(ecologyHatchPointsMap.values());
        //积分map
        List<EcologyPoints> ecologyPointsList = ecologyPointsDao.listByIds(pointsList);
        Map<Long, EcologyPoints> pointsMap = ecologyPointsList.stream().collect(Collectors.toMap(EcologyPoints::getId, e -> e));

        for (EcologyHatchIncomeConfRelevance confRelevance : relevanceList) {
            Long pointsId = ecologyHatchPointsMap.get(confRelevance.getHatchCollectionId());
            EcologyPoints ecologyPoints = pointsMap.get(pointsId);
            BigDecimal bonusPool = getLastWeekBonusPoolNew(DaoInfoEnum.META_DAO.getId(), EcologyCollectionShareProfitTypeEnum.PLATFORM_DIVIDE, confRelevance.getHatchCollectionId());
            //bonusPool小于0
            if (NumberUtil.isLessOrEqual(bonusPool, BigDecimal.ZERO)) {
                continue;
            }
            List<EcologyCollectionNodeConf> ecologyCollectionNodeConfList = ecologyCollectionNodeConfDao.listByRelevanceId(confRelevance.getId());
            if (CollectionUtils.isEmpty(ecologyCollectionNodeConfList)) {
                continue;
            }
            List<Long> collectionIds = ecologyCollectionNodeConfList.stream().map(EcologyCollectionNodeConf::getCollectionId).collect(Collectors.toList());

            //持有生态的用户
            List<Long> userIds = userCollectionService.getUserListByCollectionIds(collectionIds);
            ArrayList<UserHoldCollectionDTO> settleUser = Lists.newArrayList();
            //判断用户是否符合条件
            //用户个人持有数量
            List<UserHoldCollectionDTO> collectionIdsAndUserIdList = userCollectionService.getHoldCountByCollectionIdsAndUserIdList(userIds, collectionIds);
            if (CollectionUtils.isEmpty(collectionIdsAndUserIdList)) {
                continue;
            }
            Map<Long, Integer> holdMap = collectionIdsAndUserIdList.stream().collect(Collectors.toMap(UserHoldCollectionDTO::getUserId, UserHoldCollectionDTO::getHoldCount));
//            List<UserEcologyDTO> ecologyList = new ArrayList<>();
//            if (userIds.size() > 1000) {
//                //把List分组
//                List<List<Long>> lists = ListUtil.partition(userIds, 1000);
//                for (List<Long> longs : lists) {
//                    ecologyList.addAll(userEcologyHatchRecordsDao.getBooleanByStatusAndUserIdListPoints(longs, UserEcologyHatchRecordsStatus.UNDER_WAY,confRelevance.getHatchCollectionId()));
//                }
//            }else {
//                ecologyList = userEcologyHatchRecordsDao.getBooleanByStatusAndUserIdListPoints(userIds, UserEcologyHatchRecordsStatus.UNDER_WAY,confRelevance.getHatchCollectionId());
//
//            }
//            if (CollectionUtils.isEmpty(ecologyList)) {
//                continue;
//            }
//            Map<Long, Boolean> ecologyMap = ecologyList.stream().collect(Collectors.toMap(UserEcologyDTO::getUserId, UserEcologyDTO::getHaveEcology));

            for (Long userId : userIds) {

                Integer holdCount = holdMap.get(userId);
                if(holdCount == null) {
                    continue;
                }
//                Boolean underWayUser = ecologyMap.get(userId);
//                if (underWayUser == null) {
//                    continue;
//                }

                //判断用户是否有进行中的
                if (holdCount > 0) {
                    UserHoldCollectionDTO userHoldCollectionDTO = new UserHoldCollectionDTO();
                    userHoldCollectionDTO.setUserId(userId);
                    userHoldCollectionDTO.setHoldCount(holdCount);
                    settleUser.add(userHoldCollectionDTO);
                }
            }

            EcologyHatchIncomeConf ecologicalNodePositionAward = ecologyHatchIncomeConfDao.getAdminIncomeConfByRelevanceIdAndType(confRelevance.getId(), EcologyIncomeTypeEnum.ECOLOGICAL_NODE_POSITION_AWARD);
            BigDecimal incomeScale = ecologicalNodePositionAward.getIncomeScale().movePointLeft(2);

            Integer sumHoldCount = settleUser.stream().mapToInt(o -> Objects.isNull(o.getHoldCount()) ? 0 : o.getHoldCount()).sum();

            if (sumHoldCount > 0
                    && NumberUtil.isGreater(incomeScale, BigDecimal.ZERO)
                    && NumberUtil.isGreater(bonusPool, BigDecimal.ZERO)) {
                settleEcologyNodeTakePsitionIncomeNew(settleUser, sumHoldCount, incomeScale, bonusPool, ecologyPoints);
            }


        }


    }


    /**
     生态节点-培育奖：（只算1级）

     前置条件：
     本人持有平台节点NFT并参与对应藏品熔炼
     推荐x人熔炼该生态藏品，直推用户取消身份限制
     计算公式：
     7天培育奖=近7天（周一至周日）直推熔炼人数/近7天全平台推荐参与熔炼人数总和（分子总和）*配置比例*近7天分润池
     365天培育奖=近365天（前365天）直推熔炼人数/近365天全平台推荐参与熔炼人数总和（分子总和）*配置比例*近365天分润池
     定义：该用户直推的用户（一级）
     *
     城主-培育奖：（只算1级）

     前置条件：
     本人持有平台城主NFT并参与对应藏品熔炼
     推荐x人熔炼该生态藏品，直推用户取消身份限制
     计算公式：
     7天培育奖=近7天直推熔炼人数/近7天全平台推荐参与熔炼人数总和（分子总和）*配置比例*近7天分润池
     365天培育奖=近365天直推熔炼人数/近365天全平台推荐参与熔炼人数总和（分子总和）*配置比例*近365天分润池
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void ecologyCultivateIncomeNew() {
        //获取生态接点藏品
        //首先查询开着的配置
        List<EcologyHatchIncomeConfRelevance> relevanceList = ecologyHatchIncomeConfRelevanceDao.getOpen();
        if (CollectionUtils.isEmpty(relevanceList)) {
            return;
        }
        List<Long> hatchCollectionIdList = relevanceList.stream().map(EcologyHatchIncomeConfRelevance::getHatchCollectionId).distinct().collect(Collectors.toList());
        //熔炼查询积分
        List<EcologyHatchConf> ecologyHatchConfList = ecologyHatchConfDao.ListByCollectionId(hatchCollectionIdList);
        if (CollectionUtils.isEmpty(ecologyHatchConfList)) {
            return;
        }
        Map<Long, Long> ecologyHatchPointsMap = ecologyHatchConfList.stream().collect(Collectors.toMap(EcologyHatchConf::getCollectionId, EcologyHatchConf::getEcologyPointsId));
        List<Long> pointsList = new ArrayList<>(ecologyHatchPointsMap.values());
        //积分map
        List<EcologyPoints> ecologyPointsList = ecologyPointsDao.listByIds(pointsList);
        Map<Long, EcologyPoints> pointsMap = ecologyPointsList.stream().collect(Collectors.toMap(EcologyPoints::getId, e -> e));

        for (EcologyHatchIncomeConfRelevance confRelevance : relevanceList) {
            Long pointsId = ecologyHatchPointsMap.get(confRelevance.getHatchCollectionId());
            EcologyPoints ecologyPoints = pointsMap.get(pointsId);
            BigDecimal bonusPool = getLastWeekBonusPoolNew(DaoInfoEnum.META_DAO.getId(), EcologyCollectionShareProfitTypeEnum.PLATFORM_DIVIDE, confRelevance.getHatchCollectionId());
            //bonusPool小于0
            if (NumberUtil.isLessOrEqual(bonusPool, BigDecimal.ZERO)) {
                continue;
            }
            List<EcologyCollectionNodeConf> ecologyCollectionNodeConfList = ecologyCollectionNodeConfDao.listByRelevanceId(confRelevance.getId());
            if (CollectionUtils.isEmpty(ecologyCollectionNodeConfList)) {
                continue;
            }
            List<Long> collectionIdList = ecologyCollectionNodeConfList.stream().map(EcologyCollectionNodeConf::getCollectionId).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(collectionIdList)) {
                settleEcologyCultivateIncomeNew(bonusPool, collectionIdList, EcologyIncomeTypeEnum.NODE_CULTIVATION_AWARD_365,
                        EcologyPointsWalletEnum.NODE_CULTIVATION_AWARD_365, confRelevance.getId(),ecologyPoints,confRelevance.getHatchCollectionId());
                settleEcologyCultivateIncomeNew(bonusPool, collectionIdList, EcologyIncomeTypeEnum.NODE_CULTIVATION_AWARD_7,
                        EcologyPointsWalletEnum.NODE_CULTIVATION_AWARD_7, confRelevance.getId(), ecologyPoints,confRelevance.getHatchCollectionId());

            }

            List<Long> collectionIds = Arrays.asList(SpecialIdEnum.CITY_LORD_ID.getCollectionId());
            settleEcologyCultivateIncomeNew(bonusPool, collectionIds, EcologyIncomeTypeEnum.ECOLOGICAL_CULTIVATION_AWARD_365,
                    EcologyPointsWalletEnum.ECOLOGICAL_CULTIVATION_AWARD_365, confRelevance.getId(),ecologyPoints,confRelevance.getHatchCollectionId());
            settleEcologyCultivateIncomeNew(bonusPool, collectionIds, EcologyIncomeTypeEnum.ECOLOGICAL_CULTIVATION_AWARD_7,
                    EcologyPointsWalletEnum.ECOLOGICAL_CULTIVATION_AWARD_7, confRelevance.getId(),ecologyPoints,confRelevance.getHatchCollectionId());


        }


    }


    private void settleEcologyCultivateIncomeNew(BigDecimal bonusPool, List<Long> collectionIds,
                                                 EcologyIncomeTypeEnum income, EcologyPointsWalletEnum ecologyPointsWalletEnum,
                                                 Long relevanceId, EcologyPoints ecologyPoints,Long hatchCollectionId) {
        //获取持有藏品的用户
        List<Long> userIds = userCollectionService.getUserListByCollectionIds(collectionIds);
        if (CollUtil.isEmpty(userIds)) {
            return;
        }
        List<EcologyCultivateIncomeDTO> settleUsers = new ArrayList<>();
        //获取符合前置条件的用户天数
        if (userIds.size() > 1000) {
            //把List分组
            List<List<Long>> lists = ListUtil.partition(userIds, 1000);
            for (List<Long> longs : lists) {
                settleUsers.addAll(checkCultivateIncomeNew(longs, income.getDay(),hatchCollectionId));
            }
        }else {
            settleUsers = checkCultivateIncomeNew(userIds, income.getDay(),hatchCollectionId);
        }


        //符合条件的人数总和
        int platformBase = settleUsers.stream().mapToInt(o -> Objects.isNull(o.getNumberPeople()) ? 0 : o.getNumberPeople()).sum();

        //收益配置
        EcologyHatchIncomeConf incomeConf = ecologyHatchIncomeConfDao.getAdminIncomeConfByRelevanceIdAndType(relevanceId, income);

        if (NumberUtil.isGreater(bonusPool, BigDecimal.ZERO)
                && settleUsers.size() > 0
                && platformBase > 0
                && NumberUtil.isGreater(incomeConf.getIncomeScale().movePointLeft(2), BigDecimal.ZERO)) {
            //结算收益30天7天
            settleEcologyNodeCultivateIncomeNew(settleUsers, platformBase, incomeConf, bonusPool, ecologyPointsWalletEnum, income, ecologyPoints);
        }
    }


    /**
     * 生态节点培育奖
     *
     * @param settleUsers
     * @param platformBase
     * @param cologyHatchIncomeConf
     * @param bonusPool
     * @param pointsWalletEnum
     * @param incomeTypeEnum
     * @param ecologyPoints
     */
    private void settleEcologyNodeCultivateIncomeNew(List<EcologyCultivateIncomeDTO> settleUsers, int platformBase,
                                                     EcologyHatchIncomeConf cologyHatchIncomeConf, BigDecimal bonusPool,
                                                     EcologyPointsWalletEnum pointsWalletEnum, EcologyIncomeTypeEnum incomeTypeEnum,
                                                     EcologyPoints ecologyPoints) {
        for (EcologyCultivateIncomeDTO settleUser : settleUsers) {
            Long userId = settleUser.getUserId();
            //最近365天直推生态节点人数
            Integer numberPeople = settleUser.getNumberPeople();

            BigDecimal numberPeopleBigDecimal = Convert.toBigDecimal(numberPeople);
            BigDecimal platformBaseBigDecimal = Convert.toBigDecimal(platformBase);
            BigDecimal incomeScale = cologyHatchIncomeConf.getIncomeScale().movePointLeft(2);
            BigDecimal incomeAmount = numberPeopleBigDecimal.divide(platformBaseBigDecimal, 8, BigDecimal.ROUND_DOWN).multiply(incomeScale).multiply(bonusPool).setScale(2, BigDecimal.ROUND_DOWN);


            //添加积分
            if (NumberUtil.isGreater(incomeAmount, BigDecimal.ZERO)) {

                userEcologyPointsWalletService.adjustAmount(userId, ecologyPoints.getId(), ecologyPoints.getPointsName(), incomeAmount, pointsWalletEnum, StrUtil.EMPTY);

                //用户收支表
                UserEcologyExpenditureRecord userEcologyExpenditureRecord = new UserEcologyExpenditureRecord();
                userEcologyExpenditureRecord.setUserId(userId);
                userEcologyExpenditureRecord.setDateTime(Convert.toInt(DateUtil.format(DateTime.now(), "yyyyMMdd")));
                userEcologyExpenditureRecord.setType(UserEcologyExpenditureTypeEnum.ECOLOGY_MARK);
                userEcologyExpenditureRecord.setTypeName(UserEcologyExpenditureTypeEnum.ECOLOGY_MARK.getDescription());
                userEcologyExpenditureRecord.setRemark(incomeTypeEnum.getDescription());
                userEcologyExpenditureRecord.setLinkId(ecologyPoints.getId());
                userEcologyExpenditureRecord.setLinkName(UserEcologyExpenditureTypeEnum.ECOLOGY_MARK.getDescription());
                userEcologyExpenditureRecord.setLinkCount(incomeAmount);
                userEcologyExpenditureRecord.setLinkImage(StrUtil.EMPTY);
                userEcologyExpenditureRecord.insert();
            }
        }
    }


    private void settleEcologyNodeTakePsitionIncomeNew(ArrayList<UserHoldCollectionDTO> settleUser, Integer sumHoldCount, BigDecimal incomeScale, BigDecimal bonusPool, EcologyPoints ecologyPoints) {

        for (UserHoldCollectionDTO userHoldCollectionDTO : settleUser) {

            Integer holdCount = userHoldCollectionDTO.getHoldCount();
            Long userId = userHoldCollectionDTO.getUserId();

            BigDecimal incomeAmount = Convert.toBigDecimal(holdCount).divide(Convert.toBigDecimal(sumHoldCount), 8, BigDecimal.ROUND_DOWN).multiply(incomeScale).multiply(bonusPool).setScale(2, BigDecimal.ROUND_DOWN);

            //添加积分
            if (NumberUtil.isGreater(incomeAmount, BigDecimal.ZERO)) {
                userEcologyPointsWalletService.adjustAmount(userId, ecologyPoints.getId(), ecologyPoints.getPointsName(), incomeAmount, EcologyPointsWalletEnum.ECOLOGICAL_NODE_POSITION_AWARD, StrUtil.EMPTY);
                //用户收支表
                UserEcologyExpenditureRecord userEcologyExpenditureRecord = new UserEcologyExpenditureRecord();
                userEcologyExpenditureRecord.setUserId(userId);
                userEcologyExpenditureRecord.setDateTime(Convert.toInt(DateUtil.format(DateTime.now(), "yyyyMMdd")));
                userEcologyExpenditureRecord.setType(UserEcologyExpenditureTypeEnum.ECOLOGY_MARK);
                userEcologyExpenditureRecord.setTypeName(UserEcologyExpenditureTypeEnum.ECOLOGY_MARK.getDescription());
                userEcologyExpenditureRecord.setRemark(EcologyPointsWalletEnum.ECOLOGICAL_NODE_POSITION_AWARD.getDescription());
                userEcologyExpenditureRecord.setLinkId(ecologyPoints.getId());
                userEcologyExpenditureRecord.setLinkName(UserEcologyExpenditureTypeEnum.ECOLOGY_MARK.getDescription());
                userEcologyExpenditureRecord.setLinkCount(incomeAmount);
                userEcologyExpenditureRecord.setLinkImage(StrUtil.EMPTY);
                userEcologyExpenditureRecord.insert();
            }
        }
    }


    /**
     * 生态节点贡献奖-城主贡献奖
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void ecologyContributionIncomeNew() {

        //获取生态接点藏品
        //首先查询开着的配置
        List<EcologyHatchIncomeConfRelevance> relevanceList = ecologyHatchIncomeConfRelevanceDao.getOpen();
        if (CollectionUtils.isEmpty(relevanceList)) {
            return;
        }
        List<Long> hatchCollectionIdList = relevanceList.stream().map(EcologyHatchIncomeConfRelevance::getHatchCollectionId).distinct().collect(Collectors.toList());
        //熔炼查询积分
        List<EcologyHatchConf> ecologyHatchConfList = ecologyHatchConfDao.ListByCollectionId(hatchCollectionIdList);
        if (CollectionUtils.isEmpty(ecologyHatchConfList)) {
            return;
        }
        Map<Long, Long> ecologyHatchPointsMap = ecologyHatchConfList.stream().collect(Collectors.toMap(EcologyHatchConf::getCollectionId, EcologyHatchConf::getEcologyPointsId));
        List<Long> pointsList = new ArrayList<>(ecologyHatchPointsMap.values());
        //积分map
        List<EcologyPoints> ecologyPointsList = ecologyPointsDao.listByIds(pointsList);
        Map<Long, EcologyPoints> pointsMap = ecologyPointsList.stream().collect(Collectors.toMap(EcologyPoints::getId, e -> e));

        for (EcologyHatchIncomeConfRelevance confRelevance : relevanceList) {
            Long pointsId = ecologyHatchPointsMap.get(confRelevance.getHatchCollectionId());
            EcologyPoints ecologyPoints = pointsMap.get(pointsId);
            BigDecimal bonusPool = getLastWeekBonusPoolNew(DaoInfoEnum.META_DAO.getId(), EcologyCollectionShareProfitTypeEnum.PLATFORM_DIVIDE,confRelevance.getHatchCollectionId());
            //bonusPool小于0
            if (NumberUtil.isLessOrEqual(bonusPool, BigDecimal.ZERO)) {
                continue;
            }
            List<EcologyCollectionNodeConf> ecologyCollectionNodeConfList = ecologyCollectionNodeConfDao.listByRelevanceId(confRelevance.getId());
            if (CollectionUtils.isEmpty(ecologyCollectionNodeConfList)) {
                continue;
            }
            List<Long> collectionIdList = ecologyCollectionNodeConfList.stream().map(EcologyCollectionNodeConf::getCollectionId).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(collectionIdList)) {
                settleEcologyContributionIncomeNew(bonusPool, collectionIdList, EcologyIncomeTypeEnum.NODE_CONTRIBUTION_AWARD_365,
                        EcologyIncomeTypeEnum.NODE_CONTRIBUTION_AWARD_7, EcologyPointsWalletEnum.NODE_CONTRIBUTION_AWARD_365,
                        EcologyPointsWalletEnum.NODE_CONTRIBUTION_AWARD_7, confRelevance.getId(),ecologyPoints,confRelevance.getHatchCollectionId());
            }

            List<Long> collectionIds = Arrays.asList(SpecialIdEnum.CITY_LORD_ID.getCollectionId());
            settleEcologyContributionIncomeNew(bonusPool, collectionIds, EcologyIncomeTypeEnum.CONTRIBUTION_AWARD_365,
                    EcologyIncomeTypeEnum.CONTRIBUTION_AWARD_7, EcologyPointsWalletEnum.CONTRIBUTION_AWARD_365,
                    EcologyPointsWalletEnum.CONTRIBUTION_AWARD_7, confRelevance.getId(),ecologyPoints,confRelevance.getHatchCollectionId());


        }




    }


    /**
     * 社区网点生态贡献奖
     * 1: 7天内(不包含当天的前7天)
     * 2: 365天内(不包含当天的前365天)
     */
    @Override
    @Transactional
    public void communityNetworkEcologicalCultivationAwardNew() {

        //获取生态接点藏品
        //首先查询开着的配置
        List<EcologyHatchIncomeConfRelevance> relevanceList = ecologyHatchIncomeConfRelevanceDao.getOpen();
        if (CollectionUtils.isEmpty(relevanceList)) {
            return;
        }
        List<Long> hatchCollectionIdList = relevanceList.stream().map(EcologyHatchIncomeConfRelevance::getHatchCollectionId).distinct().collect(Collectors.toList());
        //熔炼查询积分
        List<EcologyHatchConf> ecologyHatchConfList = ecologyHatchConfDao.ListByCollectionId(hatchCollectionIdList);
        if (CollectionUtils.isEmpty(ecologyHatchConfList)) {
            return;
        }
        Map<Long, Long> ecologyHatchPointsMap = ecologyHatchConfList.stream().collect(Collectors.toMap(EcologyHatchConf::getCollectionId, EcologyHatchConf::getEcologyPointsId));
        List<Long> pointsList = new ArrayList<>(ecologyHatchPointsMap.values());
        //积分map
        List<EcologyPoints> ecologyPointsList = ecologyPointsDao.listByIds(pointsList);
        Map<Long, EcologyPoints> pointsMap = ecologyPointsList.stream().collect(Collectors.toMap(EcologyPoints::getId, e -> e));

        for (EcologyHatchIncomeConfRelevance confRelevance : relevanceList) {
            Long hatchCollectionId = confRelevance.getHatchCollectionId();
            Long pointsId = ecologyHatchPointsMap.get(confRelevance.getHatchCollectionId());
            EcologyPoints ecologyPoints = pointsMap.get(pointsId);
            BigDecimal bonusPool = getLastWeekBonusPoolNew(DaoInfoEnum.META_DAO.getId(), EcologyCollectionShareProfitTypeEnum.PLATFORM_DIVIDE,confRelevance.getHatchCollectionId());
            //bonusPool小于0
            if (NumberUtil.isLessOrEqual(bonusPool, BigDecimal.ZERO)) {
                continue;
            }
            //获取熔炼过当前藏品的社区网点
            List<Long> workRoomParticipateInSmeltingUserId = communityNetworkAndParticipateInSmeltingNew(hatchCollectionId);
            if (CollectionUtils.isEmpty(workRoomParticipateInSmeltingUserId)) {
                continue;
            }
            EcologyHatchIncomeConf contributionAward365 = ecologyHatchIncomeConfDao.getAdminIncomeConfByRelevanceIdAndType(confRelevance.getId(),EcologyIncomeTypeEnum.COMMUNITY_ECOLOGICAL_CONTRIBUTION_AWARD_365);
            EcologyHatchIncomeConf contributionAward7 = ecologyHatchIncomeConfDao.getAdminIncomeConfByRelevanceIdAndType(confRelevance.getId(),EcologyIncomeTypeEnum.COMMUNITY_ECOLOGICAL_CONTRIBUTION_AWARD_7);

            // 365天的分红比例
            BigDecimal incomeScale365 = contributionAward365.getIncomeScale().movePointLeft(2);
            // 7天的分红比例
            BigDecimal incomeScale7 = contributionAward7.getIncomeScale().movePointLeft(2);
            //初始化平台总业绩
            BigDecimal teamHoldToke365 = BigDecimal.ZERO;
            BigDecimal teamHoldToke7 = BigDecimal.ZERO;
            Map<Long,BigDecimal> sumPrice365Map = new HashMap<>();
            Map<Long,BigDecimal> sumPrice7Map = new HashMap<>();
            // 计算所有团队业绩的总的分红池,拿到以后循环处理,需要获取一次社区网点的排除后的当前团队的业绩数据
            for (Long userId : workRoomParticipateInSmeltingUserId) {
                // 定义一个list,获取当前排除自己的ID
                List<Long> excludeId = workRoomParticipateInSmeltingUserId.stream().filter(workRoomIds -> workRoomIds.longValue() != userId.longValue()).collect(Collectors.toList());
                // 排除对应id以及旗下数据,根据排除的id,只向下级查找
                if (CollUtil.isEmpty(excludeId)) {
                    excludeId.add(0L);
                }
                // 获取当前用户城市服务中心的id
                List<Long> excludesTheCityServiceCenterOfTheCurrentUser = userRelevanceDao.excludesTheCityServiceCenterOfTheCurrentUser(userId);
                // 获取当前社区网点下10级
                List<Long> afterExclusionUserId = userRelevanceDao.excludeSubordinateCommunityWithLv(userId, excludeId, excludesTheCityServiceCenterOfTheCurrentUser,10);
                if (CollUtil.isEmpty(afterExclusionUserId)) {
                    continue;
                }
                // 团队365天的熔炼组数
                BigDecimal sumPrice365 = userEcologyHatchRecordsDao.getHatchCountByUserIdListAndDayAndCollectionId(afterExclusionUserId, 365,hatchCollectionId);
                sumPrice365Map.put(userId,sumPrice365);
                // 团队7天的熔炼组数
                BigDecimal sumPrice7 = userEcologyHatchRecordsDao.getSumPriceByUserIdListAndLastWeekAndCollectionId(afterExclusionUserId,hatchCollectionId);
                sumPrice7Map.put(userId,sumPrice7);
                teamHoldToke365 = teamHoldToke365.add(sumPrice365);
                teamHoldToke7 = teamHoldToke7.add(sumPrice7);
            }

            for (Long userId : workRoomParticipateInSmeltingUserId) {
                BigDecimal sumPrice365 = BigDecimal.ZERO;
                BigDecimal sumPrice7 = BigDecimal.ZERO;
                if (!sumPrice365Map.containsKey(userId) && !sumPrice7Map.containsKey(userId)) {
                    continue;
                }
                sumPrice365 = sumPrice365Map.get(userId);
                sumPrice7 = sumPrice7Map.get(userId);
                if (teamHoldToke365.compareTo(BigDecimal.ZERO) > 0) {
                    addecologyNodeContributionIncomeNew(sumPrice365, teamHoldToke365, incomeScale365, bonusPool, userId,
                            EcologyIncomeTypeEnum.COMMUNITY_ECOLOGICAL_CONTRIBUTION_AWARD_365, EcologyPointsWalletEnum.COMMUNITY_ECOLOGICAL_CONTRIBUTION_AWARD_365,ecologyPoints);
                }
                if (teamHoldToke7.compareTo(BigDecimal.ZERO) > 0) {
                    addecologyNodeContributionIncomeNew(sumPrice7, teamHoldToke7, incomeScale7, bonusPool, userId,
                            EcologyIncomeTypeEnum.COMMUNITY_ECOLOGICAL_CONTRIBUTION_AWARD_7, EcologyPointsWalletEnum.COMMUNITY_ECOLOGICAL_CONTRIBUTION_AWARD_7,ecologyPoints);

                }
            }


        }





    }


    /**
     * 城市服务中心生态贡献奖
     */
    @Override
    @Transactional
    public void urbanServiceCenterEcologicalContributionNew() {
        //获取生态接点藏品
        //首先查询开着的配置
        List<EcologyHatchIncomeConfRelevance> relevanceList = ecologyHatchIncomeConfRelevanceDao.getOpen();
        if (CollectionUtils.isEmpty(relevanceList)) {
            return;
        }
        List<Long> hatchCollectionIdList = relevanceList.stream().map(EcologyHatchIncomeConfRelevance::getHatchCollectionId).distinct().collect(Collectors.toList());
        //熔炼查询积分
        List<EcologyHatchConf> ecologyHatchConfList = ecologyHatchConfDao.ListByCollectionId(hatchCollectionIdList);
        if (CollectionUtils.isEmpty(ecologyHatchConfList)) {
            return;
        }
        Map<Long, Long> ecologyHatchPointsMap = ecologyHatchConfList.stream().collect(Collectors.toMap(EcologyHatchConf::getCollectionId, EcologyHatchConf::getEcologyPointsId));
        List<Long> pointsList = new ArrayList<>(ecologyHatchPointsMap.values());
        //积分map
        List<EcologyPoints> ecologyPointsList = ecologyPointsDao.listByIds(pointsList);
        Map<Long, EcologyPoints> pointsMap = ecologyPointsList.stream().collect(Collectors.toMap(EcologyPoints::getId, e -> e));

        for (EcologyHatchIncomeConfRelevance confRelevance : relevanceList) {
            Long hatchCollectionId = confRelevance.getHatchCollectionId();
            Long pointsId = ecologyHatchPointsMap.get(confRelevance.getHatchCollectionId());
            EcologyPoints ecologyPoints = pointsMap.get(pointsId);
            BigDecimal bonusPool = getLastWeekBonusPoolNew(DaoInfoEnum.META_DAO.getId(), EcologyCollectionShareProfitTypeEnum.PLATFORM_DIVIDE,confRelevance.getHatchCollectionId());
            //bonusPool小于0
            if (NumberUtil.isLessOrEqual(bonusPool, BigDecimal.ZERO)) {
                continue;
            }
            EcologyHatchIncomeConf contributionAward365 = ecologyHatchIncomeConfDao.getAdminIncomeConfByRelevanceIdAndType(confRelevance.getId(),EcologyIncomeTypeEnum.CITY_CONTRIBUTION_AWARD_365);
            EcologyHatchIncomeConf contributionAward7 = ecologyHatchIncomeConfDao.getAdminIncomeConfByRelevanceIdAndType(confRelevance.getId(),EcologyIncomeTypeEnum.CITY_CONTRIBUTION_AWARD_7);

            // 365天的分红比例
            BigDecimal incomeScale365 = contributionAward365.getIncomeScale().movePointLeft(2);
            // 7天的分红比例
            BigDecimal incomeScale7 = contributionAward7.getIncomeScale().movePointLeft(2);

            //初始化平台总业绩
            BigDecimal teamHoldToke365 = BigDecimal.ZERO;
            BigDecimal teamHoldToke7 = BigDecimal.ZERO;
            Map<Long,BigDecimal> sumPrice365Map = new HashMap<>();
            Map<Long,BigDecimal> sumPrice7Map = new HashMap<>();

            // 城市服务中心熔炼中的数据.
            List<Long> smelterInTheCityServiceCenter = getSmelterInTheCityServiceCenterNew(hatchCollectionId);
            // 获取团队内指定天数内生态熔炼投入的燃料,排掉平级的.
            for (Long aLong : smelterInTheCityServiceCenter) {
                // 定义一个list,获取当前排除自己的ID
                List<Long> excludeId = smelterInTheCityServiceCenter.stream().filter(workRoomIds -> workRoomIds != aLong).collect(Collectors.toList());
                if (CollUtil.isEmpty(excludeId)) {
                    excludeId.add(0L);
                }
                // 获取当前城市服务中心下10级,获取10级后
                List<Long> afterExclusionUserId = userRelevanceDao.excludeCityServiceCentersWithLv(aLong, excludeId,10);
                // 一个团队的燃料.
                if (CollUtil.isEmpty(afterExclusionUserId)) {
                    continue;
                }
                BigDecimal sumPrice365 = BigDecimal.ZERO;
                BigDecimal sumPrice7 = BigDecimal.ZERO;
                sumPrice365 = userEcologyHatchRecordsDao.getHatchCountByUserIdListAndDayAndCollectionId(afterExclusionUserId, 365,hatchCollectionId);
                sumPrice365Map.put(aLong,sumPrice365);
                sumPrice7 = userEcologyHatchRecordsDao.getSumPriceByUserIdListAndLastWeekAndCollectionId(afterExclusionUserId,hatchCollectionId);
                sumPrice7Map.put(aLong,sumPrice7);
                teamHoldToke365 = teamHoldToke365.add(sumPrice365);
                teamHoldToke7 = teamHoldToke7.add(sumPrice7);

            }
            for (Long userId : smelterInTheCityServiceCenter) {
                BigDecimal sumPrice365 = BigDecimal.ZERO;
                BigDecimal sumPrice7 = BigDecimal.ZERO;
                if (!sumPrice365Map.containsKey(userId) && !sumPrice7Map.containsKey(userId)) {
                    continue;
                }
                sumPrice365 = sumPrice365Map.get(userId);
                sumPrice7 = sumPrice7Map.get(userId);
                if (teamHoldToke365.compareTo(BigDecimal.ZERO) > 0) {
                    addecologyNodeContributionIncomeNew(sumPrice365, teamHoldToke365, incomeScale365, bonusPool, userId,
                            EcologyIncomeTypeEnum.CITY_CONTRIBUTION_AWARD_365, EcologyPointsWalletEnum.city_CONTRIBUTION_AWARD_365,ecologyPoints);
                }
                if (teamHoldToke7.compareTo(BigDecimal.ZERO) > 0) {
                    addecologyNodeContributionIncomeNew(sumPrice7, teamHoldToke7, incomeScale7, bonusPool, userId,
                            EcologyIncomeTypeEnum.CITY_CONTRIBUTION_AWARD_7, EcologyPointsWalletEnum.city_CONTRIBUTION_AWARD_7,ecologyPoints);

                }
            }

        }

    }


    /**
     * 城市服务中心培育奖发放
     */
    @Override
    @Transactional
    public void ecologicalCultivationOfUrbanServiceCenterNew() {
        //获取生态接点藏品
        //首先查询开着的配置
        List<EcologyHatchIncomeConfRelevance> relevanceList = ecologyHatchIncomeConfRelevanceDao.getOpen();
        if (CollectionUtils.isEmpty(relevanceList)) {
            return;
        }
        List<Long> hatchCollectionIdList = relevanceList.stream().map(EcologyHatchIncomeConfRelevance::getHatchCollectionId).distinct().collect(Collectors.toList());
        //熔炼查询积分
        List<EcologyHatchConf> ecologyHatchConfList = ecologyHatchConfDao.ListByCollectionId(hatchCollectionIdList);
        if (CollectionUtils.isEmpty(ecologyHatchConfList)) {
            return;
        }
        Map<Long, Long> ecologyHatchPointsMap = ecologyHatchConfList.stream().collect(Collectors.toMap(EcologyHatchConf::getCollectionId, EcologyHatchConf::getEcologyPointsId));
        List<Long> pointsList = new ArrayList<>(ecologyHatchPointsMap.values());
        //积分map
        List<EcologyPoints> ecologyPointsList = ecologyPointsDao.listByIds(pointsList);
        Map<Long, EcologyPoints> pointsMap = ecologyPointsList.stream().collect(Collectors.toMap(EcologyPoints::getId, e -> e));

        for (EcologyHatchIncomeConfRelevance confRelevance : relevanceList) {
            Long hatchCollectionId = confRelevance.getHatchCollectionId();
            Long pointsId = ecologyHatchPointsMap.get(confRelevance.getHatchCollectionId());
            EcologyPoints ecologyPoints = pointsMap.get(pointsId);
            BigDecimal bonusPool = getLastWeekBonusPoolNew(DaoInfoEnum.META_DAO.getId(), EcologyCollectionShareProfitTypeEnum.PLATFORM_DIVIDE,confRelevance.getHatchCollectionId());
            //bonusPool小于0
            if (NumberUtil.isLessOrEqual(bonusPool, BigDecimal.ZERO)) {
                continue;
            }
            EcologyHatchIncomeConf contributionAward365 = ecologyHatchIncomeConfDao.getAdminIncomeConfByRelevanceIdAndType(confRelevance.getId(),EcologyIncomeTypeEnum.CITY_CULTIVATION_AWARD_365);
            EcologyHatchIncomeConf contributionAward7 = ecologyHatchIncomeConfDao.getAdminIncomeConfByRelevanceIdAndType(confRelevance.getId(),EcologyIncomeTypeEnum.CITY_CULTIVATION_AWARD_7);
            // 参与熔炼当前藏品的城市服务中心id
            List<Long> participationSmeltUserIds365 = ecologyIngServiceCenter(hatchCollectionId);
            if (CollUtil.isEmpty(participationSmeltUserIds365)) {
                log.info("城市服务中心365天培育奖发放失败.失败原因,参与熔炼城市服务中心id为空");
            }
            List<EcologyCultivateIncomeDTO> cityServiceCenterRecommendationsNew = getCityServiceCenterRecommendationsNew(participationSmeltUserIds365,365,hatchCollectionId);
            // 有效的城市服务中心
            List<EcologyCultivateIncomeDTO> cityServiceCenterRecommendationsStream = cityServiceCenterRecommendationsNew.stream().filter(ecologyCultivateIncomeDTO -> !ecologyCultivateIncomeDTO.getNumberPeople().equals(0)).collect(Collectors.toList());
            int sum365 = cityServiceCenterRecommendationsStream.stream().mapToInt(EcologyCultivateIncomeDTO::getNumberPeople).sum();
            // 365天奖励发放奖励
            settleEcologyNodeCultivateIncomeNew(cityServiceCenterRecommendationsStream, sum365, contributionAward365,
                    bonusPool, EcologyPointsWalletEnum.city_CULTIVATION_AWARD_365, EcologyIncomeTypeEnum.CITY_CULTIVATION_AWARD_365,
                    ecologyPoints);
            List<Long> participationSmeltUserIds7 = ecologyIngServiceCenter(hatchCollectionId);
            if (CollUtil.isEmpty(participationSmeltUserIds7)) {
                log.info("城市服务中心7天培育奖发放失败.失败原因,参与熔炼城市服务中心id为空");
            }
            List<EcologyCultivateIncomeDTO> cityServiceCenterRecommendations7 = getCityServiceCenterRecommendationsNew(participationSmeltUserIds7,7,hatchCollectionId);
            // 有效的城市服务中心
            List<EcologyCultivateIncomeDTO> cityServiceCenterRecommendationsStream7 = cityServiceCenterRecommendations7.stream().filter(ecologyCultivateIncomeDTO -> !ecologyCultivateIncomeDTO.getNumberPeople().equals(0)).collect(Collectors.toList());
            int sum7 = cityServiceCenterRecommendationsStream7.stream().mapToInt(EcologyCultivateIncomeDTO::getNumberPeople).sum();
            // 7天奖励发放奖励.
            settleEcologyNodeCultivateIncomeNew(cityServiceCenterRecommendationsStream7, sum7, contributionAward7, bonusPool,
                    EcologyPointsWalletEnum.city_CULTIVATION_AWARD_7, EcologyIncomeTypeEnum.CITY_CULTIVATION_AWARD_7,ecologyPoints);

        }
    }


    private List<EcologyCultivateIncomeDTO> getCityServiceCenterRecommendationsNew(List<Long> participationSmeltUserIds,int day,Long collectionId) {
        // 根据城市服务中心的id.获取城市服务中心的下级是否有城市服务中心,只包含直推1级
        List<EcologyCultivateIncomeDTO> ecologyCultivateIncomes = new ArrayList<>();
        for (Long participationSmeltUserId : participationSmeltUserIds) {
            EcologyCultivateIncomeDTO ecologyCultivateIncomeDTO = new EcologyCultivateIncomeDTO();
            // 通过id,和集合,获取下级城市服务中心的id,获取对应的数量.
//            return userEcologyHatchRecordsDao.recentlyDaySmelt(allUserCityServerCentreUserId, UserEcologyHatchRecordsStatus.UNDER_WAY, day,collectionId);
//            List<UserRelevance> byUserIdAndLv = userRelevanceDao.ListByUserIdAndRelevanceIdAndLv(participationSmeltUserId, participationSmeltUserIds,10);
            List<UserRelevance> byUserIdAndLv = userRelevanceDao.ListByUserIdAndRelevanceIdAndLvAndDayCollection(participationSmeltUserId,participationSmeltUserIds, day,10,collectionId,UserEcologyHatchRecordsStatus.UNDER_WAY);
            if (CollectionUtils.isEmpty(byUserIdAndLv)) {
                continue;
            }

            //判断是否是同一线上的
            int count = this.lateralTruncated(byUserIdAndLv);
            if (count == 0) {
                continue;
            }
            ecologyCultivateIncomeDTO.setNumberPeople(count);
            ecologyCultivateIncomeDTO.setUserId(participationSmeltUserId);
            ecologyCultivateIncomes.add(ecologyCultivateIncomeDTO);

        }



        return ecologyCultivateIncomes;
    }


    private int lateralTruncated (List<UserRelevance> byUserIdAndLv) {
        int count = 0;
        if (CollectionUtils.isEmpty(byUserIdAndLv)) {
            return count;
        }
        //所有的用户
        List<Long> allUserId = byUserIdAndLv.stream().map(UserRelevance::getRelevanceId).distinct().collect(Collectors.toList());
        List<Long> allFilterList = new ArrayList<>();
        Iterator<UserRelevance> mcl = byUserIdAndLv.iterator();
        while (mcl.hasNext()){
            UserRelevance next = mcl.next();
            if (!allFilterList.contains(next.getRelevanceId())) {
                List<UserRelevance> userRelevanceList = userRelevanceDao.ListByUserIdAndRelevanceIdAndLv(next.getRelevanceId(), allUserId,10 - next.getLv());
                if (!CollectionUtils.isEmpty(userRelevanceList)) {
                    List<Long> filterList = userRelevanceList.stream().map(UserRelevance::getRelevanceId).collect(Collectors.toList());
                    allFilterList.addAll(filterList);
                }
                count ++;
            }
            mcl.remove();
        }
        return count;
    }

    /**
     * 获取熔炼过当前藏品的社区网点
     * @return
     */
    private List<Long> communityNetworkAndParticipateInSmeltingNew(Long hatchCollectionId) {
        List<UserWorkRoom> list = userWorkRoomDao.list();
        List<Long> juniorUserIds = list.stream().map(UserWorkRoom::getUserId).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(juniorUserIds)) {
            return new ArrayList<>();
        }
        return userEcologyHatchRecordsDao.getListByUserIdsAndCollectionIdAndStatusAndGtCount(juniorUserIds, UserEcologyHatchRecordsStatus.UNDER_WAY, 0,hatchCollectionId);
    }

    /**
     * 结算贡献奖
     *
     * @param bonusPool
     * @param collectionIds
     * @param incomeTypeEnum365
     * @param incomeTypeEnum7
     * @param ecologyPointsWalletEnum365
     * @param ecologyPointsWalletEnum7
     */
    private void settleEcologyContributionIncomeNew(BigDecimal bonusPool, List<Long> collectionIds,
                                                    EcologyIncomeTypeEnum incomeTypeEnum365, EcologyIncomeTypeEnum incomeTypeEnum7,
                                                    EcologyPointsWalletEnum ecologyPointsWalletEnum365,
                                                    EcologyPointsWalletEnum ecologyPointsWalletEnum7,
                                                    Long confRelevanceId,EcologyPoints ecologyPoints,Long hatchCollectionId) {

        List<Long> userIdList = userCollectionService.getUserListByCollectionIds(collectionIds);
        if (CollUtil.isEmpty(userIdList)) {
            return;
        }

        List<Long> userIds = new ArrayList<>();
        //获取符合前置条件的用户天数
        if (userIdList.size() > 1000) {
            //把List分组
            List<List<Long>> lists = ListUtil.partition(userIdList, 1000);
            for (List<Long> longs : lists) {
                userIds.addAll(checkEcologyNodeContributionIncomeNew(longs,hatchCollectionId));
            }
        }else {
            userIds = checkEcologyNodeContributionIncomeNew(userIdList, hatchCollectionId);
        }




        if (CollUtil.isEmpty(userIds)) {
            log.info("生态:{}贡献奖:没有需要结算的用户", incomeTypeEnum365.getStanding());
            return;
        }

        //获取 最近30天平台用户生态熔炼投入生态燃料(不包含当天的前30天)

        EcologyHatchIncomeConf contributionAward365 = ecologyHatchIncomeConfDao.getAdminIncomeConfByRelevanceIdAndType(confRelevanceId,incomeTypeEnum365);
        EcologyHatchIncomeConf contributionAward7 = ecologyHatchIncomeConfDao.getAdminIncomeConfByRelevanceIdAndType(confRelevanceId,incomeTypeEnum7);
        BigDecimal incomeScale365 = contributionAward365.getIncomeScale().movePointLeft(2);
        BigDecimal incomeScale7 = contributionAward7.getIncomeScale().movePointLeft(2);

        List<EcologyHatchEffectiveTeamTokenDTO> settleList = Lists.newArrayList();

        BigDecimal teamHoldTokenMonth = BigDecimal.ZERO;
        BigDecimal teamHoldTokenDay = BigDecimal.ZERO;

        for (Long userId : userIds) {
            EcologyHatchEffectiveTeamTokenDTO effectiveTeamTokendto = getEffectiveTeamTokenNew(userId,hatchCollectionId);
            settleList.add(effectiveTeamTokendto);
            teamHoldTokenMonth = teamHoldTokenMonth.add(effectiveTeamTokendto.getTeamToken365());
            teamHoldTokenDay = teamHoldTokenDay.add(effectiveTeamTokendto.getTeamToken7());
        }


        for (EcologyHatchEffectiveTeamTokenDTO ecologyHatchEffectiveTeamTokenDTO : settleList) {
            BigDecimal effectiveTeamToken365 = ecologyHatchEffectiveTeamTokenDTO.getTeamToken365();
            if (NumberUtil.isGreater(incomeScale365, BigDecimal.ZERO)
                    && NumberUtil.isGreater(effectiveTeamToken365, BigDecimal.ZERO)
                    && NumberUtil.isGreater(teamHoldTokenMonth, BigDecimal.ZERO)
                    && NumberUtil.isGreater(bonusPool, BigDecimal.ZERO)) {
                //365天的收益
                addecologyNodeContributionIncomeNew(effectiveTeamToken365, teamHoldTokenMonth, incomeScale365, bonusPool,
                        ecologyHatchEffectiveTeamTokenDTO.getUserId(), incomeTypeEnum365, ecologyPointsWalletEnum365,ecologyPoints);
            }


            BigDecimal effectiveTeamToken7 = ecologyHatchEffectiveTeamTokenDTO.getTeamToken7();
            if (NumberUtil.isGreater(incomeScale7, BigDecimal.ZERO)
                    && NumberUtil.isGreater(effectiveTeamToken7, BigDecimal.ZERO)
                    && NumberUtil.isGreater(teamHoldTokenDay, BigDecimal.ZERO)
                    && NumberUtil.isGreater(bonusPool, BigDecimal.ZERO)) {
                //7天的收益
                addecologyNodeContributionIncomeNew(effectiveTeamToken7, teamHoldTokenDay, incomeScale7, bonusPool,
                        ecologyHatchEffectiveTeamTokenDTO.getUserId(), incomeTypeEnum7, ecologyPointsWalletEnum7,ecologyPoints);
            }
        }


    }

    /**
     * 每份分账流入分账池
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void disposeShareProfitDaoPool() {
        // 获取未处理的每份分账的分润记录
        List<NewEcologyHatchShareProfit> hatchShareProfits = newEcologyHatchShareProfitDao.getListByTypeAndStarts(EcologyCollectionShareProfitTypeEnum.PER_DIVIDEND_POOL, NewEcologyHatchShareProfitStatus.TO_BE_PROCESSED);
        if (CollectionUtils.isEmpty(hatchShareProfits)) {
            return;
        }
        // 熔炼记录对应的每份分账的分润记录
        Map<Long, List<NewEcologyHatchShareProfit>> hatchShareProfitsOfUserRecordIdMap = hatchShareProfits.stream()
                .collect(Collectors.groupingBy(NewEcologyHatchShareProfit::getUserRecordId));
        // 获取所有的熔炼记录
        List<Long> userRecordIdList = hatchShareProfits.stream().map(NewEcologyHatchShareProfit::getUserRecordId).collect(Collectors.toList());
        List<UserEcologyHatchRecords> userEcologyHatchRecordsList = userEcologyHatchRecordsDao.getListByIds(userRecordIdList);
        for (UserEcologyHatchRecords userEcologyHatchRecords : userEcologyHatchRecordsList) {
            Long ecologyHatchId = userEcologyHatchRecords.getEcologyHatchId();
            Long collectionId = userEcologyHatchRecords.getCollectionId();
            Long userInDaoId = userEcologyHatchRecords.getUserInDaoId();
            List<NewEcologyHatchShareProfit> newEcologyHatchShareProfits = hatchShareProfitsOfUserRecordIdMap.get(userEcologyHatchRecords.getId());
            for (NewEcologyHatchShareProfit newEcologyHatchShareProfit : newEcologyHatchShareProfits) {
                // 添加到分润池
                Long poolId = shareProfitDaoPoolService.addAmount(ecologyHatchId, collectionId, newEcologyHatchShareProfit.getDaoId(), userInDaoId, newEcologyHatchShareProfit.getPointsId(), newEcologyHatchShareProfit.getDistributionPoints(), newEcologyHatchShareProfit.getSettleTime());
                newEcologyHatchShareProfitDao.updateSettleStatusById(newEcologyHatchShareProfit.getId(), NewEcologyHatchShareProfitStatus.PROCESSING_SUCCESS, poolId);
            }
        }
    }

    /**
     * 分账池流入钱包以及技术服务费
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void theDividingPoolFlowsIntoTheWallet() {
        // 技术服务费转入
        List<NewEcologyHatchShareProfit> list = newEcologyHatchShareProfitDao.getListByTypeAndStarts(EcologyCollectionShareProfitTypeEnum.TECHNICAL_SERVICE_FEE, NewEcologyHatchShareProfitStatus.TO_BE_PROCESSED);
        for (NewEcologyHatchShareProfit newEcologyHatchShareProfit : list) {
            EcologyPoints ecologyPoints = ecologyPointsService.getById(newEcologyHatchShareProfit.getPointsId());
            String pointName = "";
            if (Objects.nonNull(ecologyPoints)) {
                pointName = ecologyPoints.getPointsName();
            }
            daoEcologyPointsWalletService.adjustAmount(newEcologyHatchShareProfit.getDaoId(), newEcologyHatchShareProfit.getPointsId()
                    , pointName, newEcologyHatchShareProfit.getDistributionPoints(), DaoEcologyPointsWalletLogTypeEnum.TRANSFER_OF_TECHNICAL_SERVICE_FEE, DaoEcologyPointsWalletLogTypeEnum.TRANSFER_OF_TECHNICAL_SERVICE_FEE.getDescription());
        }
        // 这个月开始时间
        Date now = DateUtil.beginOfMonth(new Date());
        // 获取新生态藏品分润服务中心配置
        List<EcologyShareProfitServiceCenterConf> serviceCenterConfList = ecologyShareProfitServiceCenterConfService.listByConfId(null);
        for (EcologyShareProfitServiceCenterConf ecologyShareProfitServiceCenterConf : serviceCenterConfList) {
            // 判断服务中心是否符合条件
            UserCreatorInfo serviceCenterDao = userCreatorInfoDao.getById(ecologyShareProfitServiceCenterConf.getDaoId());
            // 获取服务中心拉新人数
            Integer daoNewUserNum = userInfoDao.getDaoNewUserNum(serviceCenterDao.getUserId(), serviceCenterDao.getOnlineTime());
            // 服务中心熔炼数量
            Integer recordInDaoNum = userEcologyHatchRecordsDao.userInDaoNum(ecologyShareProfitServiceCenterConf.getConfId(), ListUtil.of(ecologyShareProfitServiceCenterConf.getDaoId()));
            if (ecologyShareProfitServiceCenterConf.getNewUserNum().intValue() <= daoNewUserNum.intValue()
                    && ecologyShareProfitServiceCenterConf.getSmeltingNum().intValue() <= recordInDaoNum.intValue()) {
                dispose(ecologyShareProfitServiceCenterConf.getConfId(),ecologyShareProfitServiceCenterConf.getDaoId(),now);
            }
        }
        // 获取所有每份分成的配置
        List<EcologyCollectionShareProfitConf> ecologyCollectionShareProfitConfList = ecologyCollectionShareProfitConfDao.getListByType(EcologyCollectionShareProfitTypeEnum.PER_DIVIDEND_POOL);
        for (EcologyCollectionShareProfitConf ecologyCollectionShareProfitConf : ecologyCollectionShareProfitConfList) {
            dispose(ecologyCollectionShareProfitConf.getConfId(),ecologyCollectionShareProfitConf.getDaoId(),now);
        }
    }

    private void dispose(Long confId,Long daoId,Date now){
        // 符合条件
        // 获取符合时间标准的池子
        List<ShareProfitDaoPool> poolList = shareProfitDaoPoolService.getListByEcologyHatchIdAndSourceDaoId(confId, daoId, Boolean.FALSE, now);
        for (ShareProfitDaoPool shareProfitDaoPool : poolList) {
            EcologyPoints ecologyPoints = ecologyPointsService.getById(shareProfitDaoPool.getPointsId());
            String pointName = "";
            if (Objects.nonNull(ecologyPoints)) {
                pointName = ecologyPoints.getPointsName();
            }
            daoEcologyPointsWalletService.adjustAmount(shareProfitDaoPool.getDaoId(), shareProfitDaoPool.getPointsId()
                    , pointName, shareProfitDaoPool.getAmount(), DaoEcologyPointsWalletLogTypeEnum.TRANSFER_INTO_THE_DIVISION_SETTLEMENT_POOL, DaoEcologyPointsWalletLogTypeEnum.TRANSFER_INTO_THE_DIVISION_SETTLEMENT_POOL.getDescription());
            shareProfitDaoPoolService.updateSettle(shareProfitDaoPool.getId(), Boolean.TRUE);
        }
    }

    private void theCityServiceCenterGivesOutIncentives(Integer day, EcologyHatchIncomeConf contributionAward365, BigDecimal platformSum7, EcologyIncomeTypeEnum ecologyIncomeTypeEnum, EcologyPointsEnum ecologyPointsEnum) {
        // 城市服务中心熔炼中的数据.
        List<Long> smelterInTheCityServiceCenter = getSmelterInTheCityServiceCenter();
        BigDecimal teamHoldToke365 = BigDecimal.ZERO;
        BigDecimal teamHoldToke7 = BigDecimal.ZERO;
        // 获取团队内指定天数内生态熔炼投入的燃料,排掉平级的.
        for (Long aLong : smelterInTheCityServiceCenter) {
            // 定义一个list,获取当前排除自己的ID
            List<Long> excludeId = smelterInTheCityServiceCenter.stream().filter(workRoomIds -> workRoomIds != aLong).collect(Collectors.toList());
            if (CollUtil.isEmpty(excludeId)) {
                excludeId.add(0L);
            }
            // 获取当前城市服务中心下10级,获取10级后,获取
            List<Long> afterExclusionUserId = userRelevanceDao.excludeCityServiceCenters(aLong, excludeId);
            // 一个团队的燃料.
            if (CollUtil.isEmpty(afterExclusionUserId)) {
                continue;
            }
            BigDecimal sumPrice = BigDecimal.ZERO;
            if (day.intValue() == 365) {
                sumPrice = userEcologyHatchRecordsDao.getSumPriceByUserIdListAndDay(afterExclusionUserId, day);
            } else {
                sumPrice = userEcologyHatchRecordsDao.getSumPriceByUserIdListAndLastWeek(afterExclusionUserId);
            }
            if (day.intValue() == 365) {
                teamHoldToke365 = teamHoldToke365.add(sumPrice);
            } else {
                teamHoldToke7 = teamHoldToke7.add(sumPrice);
            }

        }
        for (Long aLong : smelterInTheCityServiceCenter) {
            // 定义一个list,获取当前排除自己的ID
            List<Long> excludeId = smelterInTheCityServiceCenter.stream().filter(workRoomIds -> workRoomIds != aLong).collect(Collectors.toList());
            if (CollUtil.isEmpty(excludeId)) {
                excludeId.add(0L);
            }
            // 获取当前城市服务中心下10级,获取10级后,获取
            List<Long> afterExclusionUserId = userRelevanceDao.excludeCityServiceCenters(aLong, excludeId);
            // 一个团队的燃料.
            if (CollUtil.isEmpty(afterExclusionUserId)) {
                continue;
            }
            BigDecimal sumPrice = BigDecimal.ZERO;
            if (day.intValue() == 365) {
                sumPrice = userEcologyHatchRecordsDao.getSumPriceByUserIdListAndDay(afterExclusionUserId, day);
            } else {
                sumPrice = userEcologyHatchRecordsDao.getSumPriceByUserIdListAndLastWeek(afterExclusionUserId);
            }
            BigDecimal incomeScale365 = contributionAward365.getIncomeScale().movePointLeft(2);
            if (day.intValue() == 365) {
                addecologyNodeContributionIncome(sumPrice, teamHoldToke365, incomeScale365, platformSum7, aLong, ecologyIncomeTypeEnum, ecologyPointsEnum);
            } else {
                addecologyNodeContributionIncome(sumPrice, teamHoldToke7, incomeScale365, platformSum7, aLong, ecologyIncomeTypeEnum, ecologyPointsEnum);
            }
        }

    }

    private List<Long> getSmelterInTheCityServiceCenter() {
        // 获取所有城市服务中心且有正在进行的熔炼记录的用户id
        List<UserCityServerCentre> list = userCityServerCentreDao.list();
        List<Long> allUserCityServerCentreUserId = list.stream().map(UserCityServerCentre::getUserId).collect(Collectors.toList());
        return userEcologyHatchRecordsDao.getListByUserIdsAndStatusAndGtCount(allUserCityServerCentreUserId, UserEcologyHatchRecordsStatus.UNDER_WAY, 0);
    }

    private List<Long> getSmelterInTheCityServiceCenterNew(Long hatchCollectionId) {
        // 获取所有城市服务中心且有正在进行的熔炼记录的用户id
        List<UserCityServerCentre> list = userCityServerCentreDao.list();
        List<Long> allUserCityServerCentreUserId = list.stream().map(UserCityServerCentre::getUserId).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(allUserCityServerCentreUserId)) {
            return new ArrayList<>();
        }
        return userEcologyHatchRecordsDao.getListByUserIdsAndStatusAndGtCountAndCollectionId(allUserCityServerCentreUserId, UserEcologyHatchRecordsStatus.UNDER_WAY, 0,hatchCollectionId);
    }

    private List<EcologyCultivateIncomeDTO> getCityServiceCenterRecommendations(List<Long> participationSmeltUserIds) {
        // 根据城市服务中心的id.获取城市服务中心的下级是否有城市服务中心,只包含直推1级
        List<EcologyCultivateIncomeDTO> ecologyCultivateIncomes = new ArrayList<>();

        participationSmeltUserIds.forEach(participationSmeltUserId -> {
            EcologyCultivateIncomeDTO ecologyCultivateIncomeDTO = new EcologyCultivateIncomeDTO();
            // 通过id,和集合,获取下级城市服务中心的id,获取对应的数量.
            List<Long> juniorUserIds = userCityServerCentreDao.getJuniorUserIds(participationSmeltUserId, participationSmeltUserIds);
            ecologyCultivateIncomeDTO.setUserId(participationSmeltUserId);
            ecologyCultivateIncomeDTO.setNumberPeople(juniorUserIds.size());
            ecologyCultivateIncomes.add(ecologyCultivateIncomeDTO);
        });
        return ecologyCultivateIncomes;
    }

    private List<Long> participationSmeltUrbanServiceCenter(int day,Long collectionId) {
        // 获取所有城市服务中心
        List<UserCityServerCentre> list = userCityServerCentreDao.list();
        // 所有城市服务中心id
        List<Long> allUserCityServerCentreUserId = list.stream().map(UserCityServerCentre::getUserId).collect(Collectors.toList());
        // 城市服务中心参与熔炼的数据

        if (day == 365) {
            return userEcologyHatchRecordsDao.recentlyDaySmelt(allUserCityServerCentreUserId, UserEcologyHatchRecordsStatus.UNDER_WAY, day,collectionId);
        } else {
            return userEcologyHatchRecordsDao.recentlyDaySmeltLastWeek(allUserCityServerCentreUserId, UserEcologyHatchRecordsStatus.UNDER_WAY,collectionId);
        }

    }


    private List<Long> ecologyIngServiceCenter(Long collectionId) {
        // 获取所有城市服务中心
        List<UserCityServerCentre> list = userCityServerCentreDao.list();
        // 所有城市服务中心id
        List<Long> allUserCityServerCentreUserId = list.stream().map(UserCityServerCentre::getUserId).collect(Collectors.toList());
        if (CollectionUtil.isEmpty(allUserCityServerCentreUserId)) {
            return new ArrayList<>();
        }
        // 城市服务中心参与熔炼的数据
        return userEcologyHatchRecordsDao.ecologyIngServiceCenter(allUserCityServerCentreUserId, UserEcologyHatchRecordsStatus.UNDER_WAY,collectionId);


    }



    private List<Long> communityNetworkAndParticipateInSmelting() {
        List<UserWorkRoom> list = userWorkRoomDao.list();
        List<Long> juniorUserIds = list.stream().map(UserWorkRoom::getUserId).collect(Collectors.toList());
        // 获取所有社区网点并且参与熔炼的数据id.
        return userEcologyHatchRecordsDao.getListByUserIdsAndStatusAndGtCount(juniorUserIds, UserEcologyHatchRecordsStatus.UNDER_WAY, 0);
    }


    /**
     * 直推收益前置判断
     * 1.判断用户是城主或者居民 || 判断用户是否持有生态节点藏品
     * 2.判断用户是否有进行中记录
     *
     * @param userId
     * @param collectionIds
     * @return
     */
    private Boolean isSettleDirectThrustIncome(Long userId, List<Long> collectionIds) {
        Boolean isSettle = Boolean.FALSE;
        UserInfo user = userInfoService.getById(userId);
        if (ObjectUtil.isNull(user)) {
            return isSettle;
        }
        return userCollectionService.getIsHoldCollection(userId, collectionIds);
    }

    /**
     * 生态节点贡献奖  前置条件
     * <p>
     * 1.持有生态节点藏品；
     * 2.生态节点藏品持有者当前正在参与生态熔炼（有当前正在进行中的记录）
     * 3.直推至少3个生态节点，且3个生态节点都参与生态熔炼（有当前正在进行中的记录）
     */
    private List<Long> checkEcologyNodeContributionIncome(List<Long> userIds, List<Long> collectionIds) {
        List<Long> settleUserIds = Lists.newArrayList();
        for (Long userId : userIds) {
            //判断用户是否有进行中的记录
            Boolean underWayUser = userEcologyHatchRecordsDao.getBooleanByStatusAndUserId(userId, UserEcologyHatchRecordsStatus.UNDER_WAY);
            log.info("用户id:{},是否有进行中的记录:{}", userId, underWayUser);
            if (underWayUser) {
                //判断用户是否有3个直推生态节点
                List<Long> JuniorUserIds = userCollectionService.getJuniorHoldCollectionCountByCollectionIds(userId, collectionIds);
                log.info("用户id:{},直推持有藏品数量:{}", userId, JuniorUserIds.size());
                if (JuniorUserIds.size() >= 3) {
                    //判断3个直推生态节点是否都有进行中的记录
                    List<Long> count = userEcologyHatchRecordsDao.getListByUserIdsAndStatusAndGtCount(JuniorUserIds, UserEcologyHatchRecordsStatus.UNDER_WAY, 0);
                    log.info("用户id:{},直推用户是否都有进行中的记录:{}", userId, count.size());
                    if (count.size() >= 3) {
                        settleUserIds.add(userId);
                    }
                }
            }
        }
        return settleUserIds;
    }


    /**
     * 生态节点贡献奖  前置条件
     * <p>
     * 1.持有生态节点藏品；
     * 2.生态节点藏品持有者当前正在参与生态熔炼（有当前正在进行中的记录）
     * 3.直推至少3个生态节点，且3个生态节点都参与生态熔炼（有当前正在进行中的记录）
     */
    private List<Long> checkEcologyNodeContributionIncomeNew(List<Long> userIds,Long hatchCollectionId) {
        List<Long> settleUserIds = Lists.newArrayList();
        List<UserEcologyDTO> ecologyList = userEcologyHatchRecordsDao.getBooleanByStatusAndUserIdListPoints(userIds, UserEcologyHatchRecordsStatus.UNDER_WAY, hatchCollectionId);
        if (CollectionUtils.isEmpty(ecologyList)) {
            return settleUserIds;
        }
        Map<Long, Boolean> ecologyMap = ecologyList.stream().collect(Collectors.toMap(UserEcologyDTO::getUserId, UserEcologyDTO::getHaveEcology));

        List<Long> meetUserIdList = ecologyList.stream().filter(e -> e.getHaveEcology() != null && e.getHaveEcology()).map(UserEcologyDTO::getUserId).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(meetUserIdList)) {
            return settleUserIds;
        }
        List<UserRecommendDTO> recommendDTOS = userInfoService.listRecommendByUserIdList(meetUserIdList);
        //将recommendDTOS中根据RecommendUserId进行分组并且将userId转数组
        Map<Long, List<UserRecommendDTO>> recommendMap = recommendDTOS.stream().collect(Collectors.groupingBy(UserRecommendDTO::getUserId));

        for (Long userId : meetUserIdList) {
            Boolean underWayUser = ecologyMap.get(userId);
            if (underWayUser == null) {
                continue;
            }
            log.info("用户id:{},是否有进行中的记录:{}", userId, underWayUser);
            if (underWayUser) {
                List<UserRecommendDTO> recommendDTOS1 = recommendMap.get(userId);
                if (CollectionUtils.isEmpty(recommendDTOS1)) {
                    continue;
                }
                //判断用户是否有3个直推生态节点
                List<Long> JuniorUserIds = recommendDTOS1.stream().map(UserRecommendDTO::getRecommendUserId).distinct().collect(Collectors.toList());
                log.info("用户id:{},直推持有藏品数量:{}", userId, JuniorUserIds.size());
                if (JuniorUserIds.size() >= 3) {
                    //判断3个直推生态节点是否都有进行中的记录
                    List<Long> count = userEcologyHatchRecordsDao.getListByUserIdsAndStatusAndGtCountAndCollectionId(JuniorUserIds, UserEcologyHatchRecordsStatus.UNDER_WAY, 0,hatchCollectionId);
                    log.info("用户id:{},直推用户是否都有进行中的记录:{}", userId, count.size());
                    if (count.size() >= 3) {
                        settleUserIds.add(userId);
                    }
                }
            }
        }
        return settleUserIds;
    }



    /**
     * DAO贡献奖
     * 前置条件：
     * 1.持有配置的身份卡藏品；
     * 2.用户当前正在参与生态熔炼（有当前正在进行中的记录）
     * 3.直推至少X个持有配置的身份卡，且X个用户都参与生态熔炼（有当前正在进行中的记录，X取直推人数配置）
     */
    private List<Long> checkDaoEcologyNodeContributionIncome(List<Long> userIds, List<Long> holdCollectionIds, Integer directThrustUserCount) {
        List<Long> settleUserIds = Lists.newArrayList();
        for (Long userId : userIds) {
            //判断用户是否有进行中的记录
            Boolean underWayUser = userEcologyHatchRecordsDao.getBooleanByStatusAndUserId(userId, UserEcologyHatchRecordsStatus.UNDER_WAY);
            log.info("用户id:{},是否有进行中的记录:{}", userId, underWayUser);
            if (underWayUser) {
                //判断用户是否有3个直推生态节点
                List<Long> JuniorUserIds = userCollectionService.getJuniorHoldCollectionCountByCollectionIds(userId, holdCollectionIds);
                log.info("用户id:{},直推持有藏品数量:{}", userId, JuniorUserIds.size());
                if (JuniorUserIds.size() >= directThrustUserCount.intValue()) {
                    //判断3个直推生态节点是否都有进行中的记录
                    List<Long> count = userEcologyHatchRecordsDao.getListByUserIdsAndStatusAndGtCount(JuniorUserIds, UserEcologyHatchRecordsStatus.UNDER_WAY, 0);
                    log.info("用户id:{},直推用户是否都有进行中的记录:{}", userId, count.size());
                    if (count.size() >= directThrustUserCount.intValue()) {
                        settleUserIds.add(userId);
                    }
                }
            }
        }
        return settleUserIds;
    }

    /**
     * DAO贡献奖
     * 前置条件：
     * 1.持有配置的身份卡藏品；
     * 2.用户当前正在参与生态熔炼（有当前正在进行中的记录）
     * 3.直推至少X个持有配置的身份卡，且X个用户都参与生态熔炼（有当前正在进行中的记录，X取直推人数配置）
     */
    private List<Long> checkDaoEcologyNodeContributionIncomePoints(List<Long> userIds, Long hatchCollectionId, Integer directThrustUserCount) {
        List<Long> settleUserIds = Lists.newArrayList();

        List<UserEcologyDTO> ecologyList = userEcologyHatchRecordsDao.getBooleanByStatusAndUserIdListPoints(userIds, UserEcologyHatchRecordsStatus.UNDER_WAY, hatchCollectionId);
        if (CollectionUtils.isEmpty(ecologyList)) {
            return settleUserIds;
        }
        Map<Long, Boolean> ecologyMap = ecologyList.stream().collect(Collectors.toMap(UserEcologyDTO::getUserId, UserEcologyDTO::getHaveEcology));

        List<Long> meetUserIdList = ecologyList.stream().filter(e -> e.getHaveEcology() != null && e.getHaveEcology()).map(UserEcologyDTO::getUserId).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(meetUserIdList)) {
            return settleUserIds;
        }
        List<UserRecommendDTO> recommendDTOS = userInfoService.listRecommendByUserIdList(meetUserIdList);
        //将recommendDTOS中根据RecommendUserId进行分组并且将userId转数组
        Map<Long, List<UserRecommendDTO>> recommendMap = recommendDTOS.stream().collect(Collectors.groupingBy(UserRecommendDTO::getUserId));


        for (Long userId : meetUserIdList) {
            //判断自己是否参与熔炼
            Boolean underWayUser = ecologyMap.get(userId);
            if (underWayUser == null) {
                continue;
            }
            if (underWayUser) {
                //所有的下级
                List<UserRecommendDTO> recommendDTOS1 = recommendMap.get(userId);
                if (CollectionUtils.isEmpty(recommendDTOS1)) {
                    continue;
                }
                List<Long> JuniorUserIds = recommendDTOS1.stream().map(UserRecommendDTO::getRecommendUserId).distinct().collect(Collectors.toList());
                if (JuniorUserIds.size() >= directThrustUserCount.intValue()) {
                    //判断3个直推生态节点是否都有进行中的记录
                    List<Long> count = userEcologyHatchRecordsDao.getListByUserIdsAndStatusAndGtCountAndCollectionId(JuniorUserIds, UserEcologyHatchRecordsStatus.UNDER_WAY, 0,hatchCollectionId);
                    log.info("用户id:{},直推用户是否都有进行中的记录:{}", userId, count.size());
                    if (count.size() >= directThrustUserCount.intValue()) {
                        settleUserIds.add(userId);
                    }
                }
            }
        }
        return settleUserIds;
    }

    /**
     * 获取团对业绩(剔除最大直推团队投入)
     *
     * @param userId
     */
    private EcologyHatchEffectiveTeamTokenDTO getEffectiveTeamToken(Long userId) {
        List<UserInfo> recommendUserList = userInfoDao.getListByRecommendId(userId);
        //所有团队金额金额
        ArrayList<BigDecimal> list365 = Lists.newArrayList();
        ArrayList<BigDecimal> list7 = Lists.newArrayList();

        for (UserInfo info : recommendUserList) {
            //查询下面所有
            List<Long> ids = userInfoService.userRelevanceByUserId(info.getId());
            //把最上级id也加入到id集合
            ids.add(info.getId());
            //初始化团队业绩
            BigDecimal teamHoldToke365 = BigDecimal.ZERO;
            BigDecimal teamHoldToke7 = BigDecimal.ZERO;
            if (ids.size() == 0) {
                teamHoldToke365 = BigDecimal.ZERO;
                teamHoldToke7 = BigDecimal.ZERO;
            } else if (ids.size() > 1000) {//如果用户集合长度是1000的倍数 就分组
                //把List分组
                List<List<Long>> lists = ListUtil.partition(ids, 1000);
                for (List<Long> longs : lists) {
                    BigDecimal sumPrice365 = userEcologyHatchRecordsDao.getSumPriceByUserIdListAndDay(longs, 365);
                    teamHoldToke365 = teamHoldToke365.add(sumPrice365);

                    BigDecimal sumPrice7 = userEcologyHatchRecordsDao.getSumPriceByUserIdListAndLastWeek(longs);
                    teamHoldToke7 = teamHoldToke7.add(sumPrice7);
                }
            } else {
                BigDecimal sumPrice365 = userEcologyHatchRecordsDao.getSumPriceByUserIdListAndDay(ids, 365);
                teamHoldToke365 = teamHoldToke365.add(sumPrice365);

                BigDecimal sumPrice7 = userEcologyHatchRecordsDao.getSumPriceByUserIdListAndLastWeek(ids);
                teamHoldToke7 = teamHoldToke7.add(sumPrice7);
            }
            log.info("用户id:{},团队业绩365天:{},团队业绩7天:{}", info.getId(), teamHoldToke365, teamHoldToke7);
            list365.add(teamHoldToke365);
            list7.add(teamHoldToke7);
        }


        BigDecimal max365 = BigDecimal.ZERO;
        if (list365.size() > 0) {
            max365 = Collections.max(list365);
        }

        BigDecimal max7 = BigDecimal.ZERO;
        if (list365.size() > 0) {
            max7 = Collections.max(list7);
        }

        //总金额
        BigDecimal teamHoldToken365 = list365.stream().reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal teamHoldToken7 = list7.stream().reduce(BigDecimal.ZERO, BigDecimal::add);

        //有效团对业绩
        BigDecimal effectiveTeamToken365 = teamHoldToken365.subtract(max365);
        BigDecimal effectiveTeamToken7 = teamHoldToken7.subtract(max7);

        if (list365.size() == 0) {
            effectiveTeamToken365 = BigDecimal.ZERO;
        }
        if (list7.size() == 0) {
            effectiveTeamToken7 = BigDecimal.ZERO;
        }

        EcologyHatchEffectiveTeamTokenDTO ecologyHatchEffectiveTeamTokenDTO = new EcologyHatchEffectiveTeamTokenDTO();
        ecologyHatchEffectiveTeamTokenDTO.setTeamToken365(effectiveTeamToken365);
        ecologyHatchEffectiveTeamTokenDTO.setTeamToken7(effectiveTeamToken7);
        ecologyHatchEffectiveTeamTokenDTO.setUserId(userId);

        return ecologyHatchEffectiveTeamTokenDTO;

    }



    /**
     * 获取团对业绩(剔除最大直推团队投入)
     *
     * @param userId
     */
    private EcologyHatchEffectiveTeamTokenDTO getEffectiveTeamTokenNew(Long userId,Long hatchCollectionId) {
        List<Long> recommendUserList = userInfoDao.listRecommendByUserId(userId);
            //初始化团队业绩
            BigDecimal teamHoldToke365 = BigDecimal.ZERO;
            BigDecimal teamHoldToke7 = BigDecimal.ZERO;
            if (!CollectionUtils.isEmpty(recommendUserList)) {
                if (recommendUserList.size() > 1000) {//如果用户集合长度是1000的倍数 就分组
                    //把List分组
                    List<List<Long>> lists = ListUtil.partition(recommendUserList, 1000);
                    for (List<Long> longs : lists) {
                        BigDecimal sumPrice365 = userEcologyHatchRecordsDao.getHatchCountByUserIdListAndDayAndCollectionId(longs, 365,hatchCollectionId);
                        teamHoldToke365 = teamHoldToke365.add(sumPrice365);

                        BigDecimal sumPrice7 = userEcologyHatchRecordsDao.getSumPriceByUserIdListAndLastWeekAndCollectionId(longs,hatchCollectionId);
                        teamHoldToke7 = teamHoldToke7.add(sumPrice7);
                    }
                } else {
                    BigDecimal sumPrice365 = userEcologyHatchRecordsDao.getHatchCountByUserIdListAndDayAndCollectionId(recommendUserList, 365,hatchCollectionId);
                    teamHoldToke365 = teamHoldToke365.add(sumPrice365);

                    BigDecimal sumPrice7 = userEcologyHatchRecordsDao.getSumPriceByUserIdListAndLastWeekAndCollectionId(recommendUserList,hatchCollectionId);
                    teamHoldToke7 = teamHoldToke7.add(sumPrice7);
                }
            }
            log.info("用户id:{},团队业绩365天:{},团队业绩7天:{}", userId, teamHoldToke365, teamHoldToke7);


        EcologyHatchEffectiveTeamTokenDTO ecologyHatchEffectiveTeamTokenDTO = new EcologyHatchEffectiveTeamTokenDTO();
        ecologyHatchEffectiveTeamTokenDTO.setTeamToken365(teamHoldToke365);
        ecologyHatchEffectiveTeamTokenDTO.setTeamToken7(teamHoldToke7);
        ecologyHatchEffectiveTeamTokenDTO.setUserId(userId);

        return ecologyHatchEffectiveTeamTokenDTO;

    }






    private EcologyHatchEffectiveTeamTokenDTO getDaoEffectiveTeamToken(Long userId, List<Long> ecologyHatchcollectionIds, int days) {
        List<UserInfo> recommendUserList = userInfoDao.getListByRecommendId(userId);
        //所有团队金额金额
        ArrayList<BigDecimal> list365 = Lists.newArrayList();

        for (UserInfo info : recommendUserList) {
            //查询下面所有
            List<Long> ids = userInfoService.userRelevanceByUserId(info.getId());
            //把最上级id也加入到id集合
            ids.add(info.getId());
            //初始化团队业绩
            BigDecimal teamHoldToke365 = BigDecimal.ZERO;
            if (ids.size() == 0) {
                teamHoldToke365 = BigDecimal.ZERO;
            } else if (ids.size() > 1000) {//如果用户集合长度是1000的倍数 就分组
                //把List分组
                List<List<Long>> lists = ListUtil.partition(ids, 1000);
                for (List<Long> longs : lists) {
                    BigDecimal sumPrice365 = userEcologyHatchRecordsDao.getSumPriceByUserIdListAndDayAndCollectionIds(longs, ecologyHatchcollectionIds, days);
                    teamHoldToke365 = teamHoldToke365.add(sumPrice365);
                }
            } else {
                BigDecimal sumPrice365 = userEcologyHatchRecordsDao.getSumPriceByUserIdListAndDayAndCollectionIds(ids, ecologyHatchcollectionIds, days);
                teamHoldToke365 = teamHoldToke365.add(sumPrice365);
            }
            list365.add(teamHoldToke365);
        }


        BigDecimal max365 = BigDecimal.ZERO;
        if (list365.size() > 0) {
            max365 = Collections.max(list365);
        }


        //总金额
        BigDecimal teamHoldToken365 = list365.stream().reduce(BigDecimal.ZERO, BigDecimal::add);

        //有效团对业绩
        BigDecimal effectiveTeamToken365 = teamHoldToken365.subtract(max365);

        if (list365.size() == 0) {
            effectiveTeamToken365 = BigDecimal.ZERO;
        }

        EcologyHatchEffectiveTeamTokenDTO ecologyHatchEffectiveTeamTokenDTO = new EcologyHatchEffectiveTeamTokenDTO();
        ecologyHatchEffectiveTeamTokenDTO.setTeamToken365(effectiveTeamToken365);
        ecologyHatchEffectiveTeamTokenDTO.setUserId(userId);
        return ecologyHatchEffectiveTeamTokenDTO;

    }


    private EcologyHatchEffectiveTeamTokenDTO getDaoEffectiveTeamTokenNew(Long userId, Long hatchCollectionId, int days) {
        List<Long> recommendUserList = userInfoDao.listRecommendByUserId(userId);
        //初始化团队业绩
        BigDecimal teamHoldToke365 = BigDecimal.ZERO;
         if (!CollectionUtils.isEmpty(recommendUserList)) {
            if (recommendUserList.size() > 1000) {//如果用户集合长度是1000的倍数 就分组
                //把List分组
                List<List<Long>> lists = ListUtil.partition(recommendUserList, 1000);
                for (List<Long> longs : lists) {
                    BigDecimal sumPrice365 = userEcologyHatchRecordsDao.getHatchCountByUserIdListAndDayAndCollectionId(longs, days,hatchCollectionId);
                    teamHoldToke365 = teamHoldToke365.add(sumPrice365);
                }
            } else {
                BigDecimal sumPrice365 = userEcologyHatchRecordsDao.getHatchCountByUserIdListAndDayAndCollectionId(recommendUserList, days,hatchCollectionId);
                teamHoldToke365 = teamHoldToke365.add(sumPrice365);
            }
        }

        EcologyHatchEffectiveTeamTokenDTO ecologyHatchEffectiveTeamTokenDTO = new EcologyHatchEffectiveTeamTokenDTO();
        ecologyHatchEffectiveTeamTokenDTO.setTeamToken365(teamHoldToke365);
        ecologyHatchEffectiveTeamTokenDTO.setUserId(userId);
        return ecologyHatchEffectiveTeamTokenDTO;

    }



    /**
     * 生态节点贡献奖
     *
     * @param effectiveTeamToken 有效团队业绩
     * @param platformSum        平台总业绩
     * @param incomeScale        收益比例
     * @param bonusPool          分红池
     * @param userId             用户id
     * @param incomeTypeEnum     收益类型
     * @param ecologyPointsEnum  生态燃料类型
     */
    private void addecologyNodeContributionIncome(BigDecimal effectiveTeamToken, BigDecimal platformSum, BigDecimal incomeScale, BigDecimal bonusPool, Long userId, EcologyIncomeTypeEnum incomeTypeEnum, EcologyPointsEnum ecologyPointsEnum) {
        //判断用户团对有效业绩是否大于0
        if (NumberUtil.isGreater(effectiveTeamToken, BigDecimal.ZERO)) {
            BigDecimal incomeAmount = effectiveTeamToken.divide(platformSum, 8, BigDecimal.ROUND_DOWN).
                    multiply(incomeScale).
                    multiply(bonusPool).setScale(2, BigDecimal.ROUND_DOWN);
            //添加燃料
            if (NumberUtil.isGreater(incomeAmount, BigDecimal.ZERO)) {
//                userEcologyPointsService.addEcologyPoints(userId,incomeAmount,ecologyPointsEnum,StrUtil.EMPTY);

                userEcologyPointsService.addDynamicStateEcologyPoints(userId, incomeAmount, ecologyPointsEnum, incomeTypeEnum, StrUtil.EMPTY, StrUtil.EMPTY);

                //收益记录表
                UserEcologyHatchIncomeRecord userEcologyHatchIncomeRecord = new UserEcologyHatchIncomeRecord();
                userEcologyHatchIncomeRecord.setAmount(incomeAmount);
                userEcologyHatchIncomeRecord.setUserId(userId);
                userEcologyHatchIncomeRecord.setIncomeType(incomeTypeEnum);
                userEcologyHatchIncomeRecord.setIncomeTypeName(incomeTypeEnum.getDescription());
                userEcologyHatchIncomeRecord.setSourceUserId(0L);
                userEcologyHatchIncomeRecord.setOurceUserEcologyHatchRecordsId(0L);
                userEcologyHatchIncomeRecord.setSumPrizePool(bonusPool);
                userEcologyHatchIncomeRecord.setPrizePoolScale(incomeScale);
                userEcologyHatchIncomeRecord.setSumHeadCountCollectionNode(0L);
                userEcologyHatchIncomeRecord.setRecommendHeadCountCollectionNode(0L);
                userEcologyHatchIncomeRecord.setEffectiveTeamToken(effectiveTeamToken);
                userEcologyHatchIncomeRecord.setPlatformToken(platformSum);
                userEcologyHatchIncomeRecord.insert();

                //用户收支表
                UserEcologyExpenditureRecord userEcologyExpenditureRecord = new UserEcologyExpenditureRecord();
                userEcologyExpenditureRecord.setDateTime(Convert.toInt(DateUtil.format(DateTime.now(), "yyyyMMdd")));
                userEcologyExpenditureRecord.setUserId(userId);
                userEcologyExpenditureRecord.setType(UserEcologyExpenditureTypeEnum.ECOLOGY_POINTS);
                userEcologyExpenditureRecord.setTypeName(UserEcologyExpenditureTypeEnum.ECOLOGY_POINTS.getDescription());
                userEcologyExpenditureRecord.setRemark(incomeTypeEnum.getDescription());
                userEcologyExpenditureRecord.setLinkId(0l);
                userEcologyExpenditureRecord.setLinkName(UserEcologyExpenditureTypeEnum.ECOLOGY_POINTS.getDescription());
                userEcologyExpenditureRecord.setLinkCount(incomeAmount);
                userEcologyExpenditureRecord.setLinkImage(StrUtil.EMPTY);
                userEcologyExpenditureRecord.insert();
            }
        }
    }








    /**
     * 生态节点贡献奖
     *
     * @param effectiveTeamToken 有效团队业绩
     * @param platformSum        平台总业绩
     * @param incomeScale        收益比例
     * @param bonusPool          分红池
     * @param userId             用户id
     * @param incomeTypeEnum     收益类型
     * @param ecologyPointsWalletEnum  积分类型
     * @param ecologyPoints  积分
     */
    private void addecologyNodeContributionIncomeNew(BigDecimal effectiveTeamToken, BigDecimal platformSum,
                                                     BigDecimal incomeScale, BigDecimal bonusPool,
                                                     Long userId, EcologyIncomeTypeEnum incomeTypeEnum,
                                                     EcologyPointsWalletEnum ecologyPointsWalletEnum,
                                                     EcologyPoints ecologyPoints) {
        //判断用户团对有效业绩是否大于0
        if (NumberUtil.isGreater(effectiveTeamToken, BigDecimal.ZERO)) {
            BigDecimal incomeAmount = effectiveTeamToken.divide(platformSum, 8, BigDecimal.ROUND_DOWN).
                    multiply(incomeScale).
                    multiply(bonusPool).setScale(2, BigDecimal.ROUND_DOWN);
            //添加积分
            if (NumberUtil.isGreater(incomeAmount, BigDecimal.ZERO)) {
                userEcologyPointsWalletService.adjustAmount(userId,ecologyPoints.getId(),ecologyPoints.getPointsName(),incomeAmount,ecologyPointsWalletEnum,StrUtil.EMPTY);
                //用户收支表
                UserEcologyExpenditureRecord userEcologyExpenditureRecord = new UserEcologyExpenditureRecord();
                userEcologyExpenditureRecord.setUserId(userId);
                userEcologyExpenditureRecord.setDateTime(Convert.toInt(DateUtil.format(DateTime.now(), "yyyyMMdd")));
                userEcologyExpenditureRecord.setType(UserEcologyExpenditureTypeEnum.ECOLOGY_MARK);
                userEcologyExpenditureRecord.setTypeName(UserEcologyExpenditureTypeEnum.ECOLOGY_MARK.getDescription());
                userEcologyExpenditureRecord.setRemark(incomeTypeEnum.getDescription());
                userEcologyExpenditureRecord.setLinkId(ecologyPoints.getId());
                userEcologyExpenditureRecord.setLinkName(UserEcologyExpenditureTypeEnum.ECOLOGY_MARK.getDescription());
                userEcologyExpenditureRecord.setLinkCount(incomeAmount);
                userEcologyExpenditureRecord.setLinkImage(StrUtil.EMPTY);
                userEcologyExpenditureRecord.insert();
            }
        }
    }

    private void addDaoecologyNodeContributionIncome(BigDecimal effectiveTeamToken, BigDecimal platformSum, BigDecimal incomeScale, BigDecimal bonusPool, Long userId, EcologyHatchDaoIncomeConf ecologyHatchDaoIncomeConf, EcologyIncomeTypeEnum incomeTypeEnum, EcologyPointsEnum ecologyPointsEnum, Long daoId) {
        //判断用户团对有效业绩是否大于0
        if (NumberUtil.isGreater(effectiveTeamToken, BigDecimal.ZERO)) {
            BigDecimal incomeAmount = effectiveTeamToken.divide(platformSum, 8, BigDecimal.ROUND_DOWN).
                    multiply(incomeScale).
                    multiply(bonusPool).setScale(2, BigDecimal.ROUND_DOWN);

            //添加燃料
            if (NumberUtil.isGreater(incomeAmount, BigDecimal.ZERO)) {
//                userEcologyPointsService.addEcologyPoints(userId,incomeAmount,ecologyPointsEnum,StrUtil.EMPTY);

                userEcologyPointsService.addDynamicStateEcologyPoints(userId, incomeAmount, ecologyPointsEnum, incomeTypeEnum, StrUtil.EMPTY, StrUtil.format("{}({}天)", ecologyHatchDaoIncomeConf.getDividendIncomeName(), ecologyHatchDaoIncomeConf.getDimensionality().getDays()));

                //收益记录表
                UserEcologyHatchIncomeRecord userEcologyHatchIncomeRecord = new UserEcologyHatchIncomeRecord();
                userEcologyHatchIncomeRecord.setAmount(incomeAmount);
                userEcologyHatchIncomeRecord.setUserId(userId);
                userEcologyHatchIncomeRecord.setIncomeType(incomeTypeEnum);
                userEcologyHatchIncomeRecord.setIncomeTypeName(StrUtil.format("{}({}天)", ecologyHatchDaoIncomeConf.getDividendIncomeName(), ecologyHatchDaoIncomeConf.getDimensionality().getDays()));
                userEcologyHatchIncomeRecord.setSourceUserId(0L);
                userEcologyHatchIncomeRecord.setOurceUserEcologyHatchRecordsId(0L);
                userEcologyHatchIncomeRecord.setSumPrizePool(bonusPool);
                userEcologyHatchIncomeRecord.setPrizePoolScale(incomeScale);
                userEcologyHatchIncomeRecord.setSumHeadCountCollectionNode(0L);
                userEcologyHatchIncomeRecord.setRecommendHeadCountCollectionNode(0L);
                userEcologyHatchIncomeRecord.setEffectiveTeamToken(effectiveTeamToken);
                userEcologyHatchIncomeRecord.setPlatformToken(platformSum);
                userEcologyHatchIncomeRecord.setDaoId(daoId);
                userEcologyHatchIncomeRecord.insert();

                //用户收支表
                UserEcologyExpenditureRecord userEcologyExpenditureRecord = new UserEcologyExpenditureRecord();
                userEcologyExpenditureRecord.setDateTime(Convert.toInt(DateUtil.format(DateTime.now(), "yyyyMMdd")));
                userEcologyExpenditureRecord.setUserId(userId);
                userEcologyExpenditureRecord.setType(UserEcologyExpenditureTypeEnum.ECOLOGY_POINTS);
                userEcologyExpenditureRecord.setTypeName(UserEcologyExpenditureTypeEnum.ECOLOGY_POINTS.getDescription());
                userEcologyExpenditureRecord.setRemark(StrUtil.format("{}({}天)", ecologyHatchDaoIncomeConf.getDividendIncomeName(), ecologyHatchDaoIncomeConf.getDimensionality().getDays()));
                userEcologyExpenditureRecord.setLinkId(0l);
                userEcologyExpenditureRecord.setLinkName(UserEcologyExpenditureTypeEnum.ECOLOGY_POINTS.getDescription());
                userEcologyExpenditureRecord.setLinkCount(incomeAmount);
                userEcologyExpenditureRecord.setLinkImage(StrUtil.EMPTY);
                userEcologyExpenditureRecord.insert();
            }
        }
    }


    private void addDaoecologyNodeContributionIncomePoints(BigDecimal effectiveTeamToken, BigDecimal platformSum,
                                                           BigDecimal incomeScale, BigDecimal bonusPool, Long userId,
                                                           EcologyHatchDaoIncomeConf ecologyHatchDaoIncomeConf,EcologyPoints ecologyPoints) {
        //判断用户团对有效业绩是否大于0
        if (NumberUtil.isGreater(effectiveTeamToken, BigDecimal.ZERO)) {
            BigDecimal incomeAmount = effectiveTeamToken.divide(platformSum, 8, BigDecimal.ROUND_DOWN).
                    multiply(incomeScale).
                    multiply(bonusPool).setScale(2, BigDecimal.ROUND_DOWN);

            //添加积分
            if (NumberUtil.isGreater(incomeAmount, BigDecimal.ZERO)) {
                userEcologyPointsWalletService.adjustAmount(userId,ecologyPoints.getId(),ecologyPoints.getPointsName(),incomeAmount,EcologyPointsWalletEnum.DAO_CONTRIBUTION_AWARD,StrUtil.EMPTY);

                //用户收支表
                UserEcologyExpenditureRecord userEcologyExpenditureRecord = new UserEcologyExpenditureRecord();
                userEcologyExpenditureRecord.setDateTime(Convert.toInt(DateUtil.format(DateTime.now(), "yyyyMMdd")));
                userEcologyExpenditureRecord.setUserId(userId);
                userEcologyExpenditureRecord.setType(UserEcologyExpenditureTypeEnum.ECOLOGY_MARK);
                userEcologyExpenditureRecord.setTypeName(UserEcologyExpenditureTypeEnum.ECOLOGY_MARK.getDescription());
                userEcologyExpenditureRecord.setRemark(StrUtil.format("{}({}天)", ecologyHatchDaoIncomeConf.getDividendIncomeName(), ecologyHatchDaoIncomeConf.getDimensionality().getDays()));
                userEcologyExpenditureRecord.setLinkId(ecologyPoints.getId());
                userEcologyExpenditureRecord.setLinkName(UserEcologyExpenditureTypeEnum.ECOLOGY_MARK.getDescription());
                userEcologyExpenditureRecord.setLinkCount(incomeAmount);
                userEcologyExpenditureRecord.setLinkImage(StrUtil.EMPTY);
                userEcologyExpenditureRecord.insert();
            }
        }
    }


    /**
     * 获取符合培育奖前置条件的用户id集合
     *
     * @param collectionIds 节点藏品集合
     *                      <p>
     *                      最近365天直推生态节点人数
     *                      最近7天新增直推生态节点人数
     * @return
     */
    private List<EcologyCultivateIncomeDTO> checkCultivateIncome(List<Long> userIds, List<Long> collectionIds, Integer day) {
        ArrayList<EcologyCultivateIncomeDTO> list = Lists.newArrayList();
        for (Long userId : userIds) {
            //判断自己是否参与熔炼
            if (!userEcologyHatchRecordsDao.getBooleanByStatusAndUserId(userId, UserEcologyHatchRecordsStatus.UNDER_WAY)) {
                continue;
            }

            //所有的下级持有的
            List<Long> juniorUserList = userCollectionService.getJuniorHoldCollectionCountByCollectionIds(userId, collectionIds);
            int numberPeople = 0;
            if (juniorUserList.size() > 0) {
                //获取下级存在熔炼记录的人数
                if (day.intValue() == 365) {
                    numberPeople = userEcologyHatchRecordsDao.getCountByUserIdsAndStatusAndDay(juniorUserList, UserEcologyHatchRecordsStatus.UNDER_WAY, day);
                } else if (day.intValue() == 7) {//查询上周熔炼的人数
                    numberPeople = userEcologyHatchRecordsDao.getCountByUserIdsAndStatusAndLastWeek(juniorUserList, UserEcologyHatchRecordsStatus.UNDER_WAY);
                } else if (day.intValue() == 30) {
                    numberPeople = userEcologyHatchRecordsDao.getCountByUserIdsAndStatusAndDay(juniorUserList, UserEcologyHatchRecordsStatus.UNDER_WAY, day);
                }
            }

            if (numberPeople > 0) {//如果有符合条件的 则加入发放奖励集合
                EcologyCultivateIncomeDTO ecologyCultivateIncomeDTO = new EcologyCultivateIncomeDTO();
                ecologyCultivateIncomeDTO.setUserId(userId);
                ecologyCultivateIncomeDTO.setNumberPeople(numberPeople);
                list.add(ecologyCultivateIncomeDTO);
            }
        }
        return list;
    }


    private List<EcologyCultivateIncomeDTO> checkCultivateIncomeNew(List<Long> userIds, Integer day,Long hatchCollectionId) {
        ArrayList<EcologyCultivateIncomeDTO> list = Lists.newArrayList();
        List<UserEcologyDTO> ecologyList = userEcologyHatchRecordsDao.getBooleanByStatusAndUserIdListPoints(userIds, UserEcologyHatchRecordsStatus.UNDER_WAY,hatchCollectionId);
        if (CollectionUtils.isEmpty(ecologyList)) {
            return list;
        }
        Map<Long, Boolean> ecologyMap = ecologyList.stream().collect(Collectors.toMap(UserEcologyDTO::getUserId, UserEcologyDTO::getHaveEcology));

        List<Long> meetUserIdList = ecologyList.stream().filter(e -> e.getHaveEcology() != null && e.getHaveEcology()).map(UserEcologyDTO::getUserId).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(meetUserIdList)) {
            return list;
        }
        List<UserRecommendDTO> recommendDTOS = userInfoService.listRecommendByUserIdList(meetUserIdList);
        //将recommendDTOS中根据RecommendUserId进行分组并且将userId转数组
        Map<Long, List<UserRecommendDTO>> recommendMap = recommendDTOS.stream().collect(Collectors.groupingBy(UserRecommendDTO::getUserId));

        for (Long userId : meetUserIdList) {
            Boolean underWayUser = ecologyMap.get(userId);
            if (underWayUser == null) {
                continue;
            }
            //判断自己是否参与熔炼
            if (!underWayUser) {
                continue;
            }
            List<UserRecommendDTO> recommendDTOS1 = recommendMap.get(userId);
            if (CollectionUtils.isEmpty(recommendDTOS1)) {
                continue;
            }
            //
            List<Long> juniorUserList = recommendDTOS1.stream().map(UserRecommendDTO::getRecommendUserId).distinct().collect(Collectors.toList());
            int numberPeople = 0;
            if (juniorUserList.size() > 0) {
                //获取下级存在熔炼记录的人数
                if (day.intValue() == 365) {
                    numberPeople = userEcologyHatchRecordsDao.getCountByUserIdsAndStatusAndDayAndCollectionId(juniorUserList, UserEcologyHatchRecordsStatus.UNDER_WAY, day,hatchCollectionId);
                } else if (day.intValue() == 7){//查询上周熔炼的人数
                    numberPeople = userEcologyHatchRecordsDao.getCountByUserIdsAndStatusAndLastWeekAndCollectionId(juniorUserList, UserEcologyHatchRecordsStatus.UNDER_WAY,hatchCollectionId);
                } else if (day.intValue() == 30) {
                    numberPeople = userEcologyHatchRecordsDao.getCountByUserIdsAndStatusAndDayAndCollectionId(juniorUserList, UserEcologyHatchRecordsStatus.UNDER_WAY, day,hatchCollectionId);
                }
            }

            if (numberPeople > 0) {//如果有符合条件的 则加入发放奖励集合
                EcologyCultivateIncomeDTO ecologyCultivateIncomeDTO = new EcologyCultivateIncomeDTO();
                ecologyCultivateIncomeDTO.setUserId(userId);
                ecologyCultivateIncomeDTO.setNumberPeople(numberPeople);
                list.add(ecologyCultivateIncomeDTO);
            }
        }
        return list;
    }

    /**
     * 校验DAO培育奖
     *
     * @param userIds
     * @param holdCollectionIds         持有的藏品
     * @param ecologyHatchcollectionIds 熔炼的藏品
     * @param day
     * @return
     */
    private List<EcologyCultivateIncomeDTO> checkDAOCultivateIncome(List<Long> userIds, List<Long> holdCollectionIds, List<Long> ecologyHatchcollectionIds, Integer day, Integer directThrustUserCount) {
        ArrayList<EcologyCultivateIncomeDTO> list = Lists.newArrayList();
        for (Long userId : userIds) {
            //判断自己是否参与熔炼
            if (!userEcologyHatchRecordsDao.getBooleanByStatusAndUserId(userId, UserEcologyHatchRecordsStatus.UNDER_WAY)) {
                continue;
            }

            //所有的下级持有的
            List<Long> juniorUserList = userCollectionService.getJuniorHoldCollectionCountByCollectionIds(userId, holdCollectionIds);
            int numberPeople = 0;
            if (juniorUserList.size() >= directThrustUserCount.intValue()) {
                //获取下级存在熔炼记录的人数
                numberPeople = userEcologyHatchRecordsDao.getCountByUserIdsAndEcologyHatchcollectionIdsAndStatusAndDay(juniorUserList, ecologyHatchcollectionIds, UserEcologyHatchRecordsStatus.UNDER_WAY, day);
            }

            if (numberPeople >= directThrustUserCount.intValue()) {//如果有符合条件的 则加入发放奖励集合
                EcologyCultivateIncomeDTO ecologyCultivateIncomeDTO = new EcologyCultivateIncomeDTO();
                ecologyCultivateIncomeDTO.setUserId(userId);
                ecologyCultivateIncomeDTO.setNumberPeople(numberPeople);
                list.add(ecologyCultivateIncomeDTO);
            }
        }
        return list;
    }

    private List<EcologyCultivateIncomeDTO> checkDAOCultivateIncomePoints(List<Long> userIds, Long hatchCollectionId, Integer day, Integer directThrustUserCount) {
        ArrayList<EcologyCultivateIncomeDTO> list = Lists.newArrayList();

        List<UserEcologyDTO> ecologyList = userEcologyHatchRecordsDao.getBooleanByStatusAndUserIdListPoints(userIds, UserEcologyHatchRecordsStatus.UNDER_WAY, hatchCollectionId);
        if (CollectionUtils.isEmpty(ecologyList)) {
            return list;
        }
        Map<Long, Boolean> ecologyMap = ecologyList.stream().collect(Collectors.toMap(UserEcologyDTO::getUserId, UserEcologyDTO::getHaveEcology));

        List<Long> meetUserIdList = ecologyList.stream().filter(e -> e.getHaveEcology() != null && e.getHaveEcology()).map(UserEcologyDTO::getUserId).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(meetUserIdList)) {
            return list;
        }
        List<UserRecommendDTO> recommendDTOS = userInfoService.listRecommendByUserIdList(meetUserIdList);
        //将recommendDTOS中根据RecommendUserId进行分组并且将userId转数组
        Map<Long, List<UserRecommendDTO>> recommendMap = recommendDTOS.stream().collect(Collectors.groupingBy(UserRecommendDTO::getUserId));


        for (Long userId : meetUserIdList) {
            //判断自己是否参与熔炼

            Boolean underWayUser = ecologyMap.get(userId);
            if (underWayUser == null) {
                continue;
            }
            if (!underWayUser) {
                continue;
            }
            List<UserRecommendDTO> recommendDTOS1 = recommendMap.get(userId);
            if (CollectionUtils.isEmpty(recommendDTOS1)) {
                continue;
            }

            //所有的下级
            List<Long> juniorUserList = recommendDTOS1.stream().map(UserRecommendDTO::getRecommendUserId).distinct().collect(Collectors.toList());
            int numberPeople = 0;
            if (juniorUserList.size() >= directThrustUserCount.intValue()) {
                //获取下级存在熔炼记录的人数
                numberPeople = userEcologyHatchRecordsDao.getCountByUserIdsAndEcologyHatchCollectionIdsAndStatusAndDayPoints(juniorUserList, hatchCollectionId, UserEcologyHatchRecordsStatus.UNDER_WAY, day);
            }
            if (numberPeople >= directThrustUserCount.intValue()) {//如果有符合条件的 则加入发放奖励集合
                EcologyCultivateIncomeDTO ecologyCultivateIncomeDTO = new EcologyCultivateIncomeDTO();
                ecologyCultivateIncomeDTO.setUserId(userId);
                ecologyCultivateIncomeDTO.setNumberPeople(numberPeople);
                list.add(ecologyCultivateIncomeDTO);
            }
        }
        return list;
    }

    /**
     * 生态节点培育奖
     *
     * @param settleUsers
     * @param platformBase
     * @param cologyHatchIncomeConf
     * @param bonusPool
     * @param ecologyPointsEnum
     * @param incomeTypeEnum
     */
    private void settleEcologyNodeCultivateIncome(List<EcologyCultivateIncomeDTO> settleUsers, int platformBase, EcologyHatchIncomeConf cologyHatchIncomeConf, BigDecimal bonusPool, EcologyPointsEnum ecologyPointsEnum, EcologyIncomeTypeEnum incomeTypeEnum) {
        for (EcologyCultivateIncomeDTO settleUser : settleUsers) {
            Long userId = settleUser.getUserId();
            //最近365天直推生态节点人数
            Integer numberPeople = settleUser.getNumberPeople();

            BigDecimal numberPeopleBigDecimal = Convert.toBigDecimal(numberPeople);
            BigDecimal platformBaseBigDecimal = Convert.toBigDecimal(platformBase);
            BigDecimal incomeScale = cologyHatchIncomeConf.getIncomeScale().movePointLeft(2);
            BigDecimal incomeAmount = numberPeopleBigDecimal.divide(platformBaseBigDecimal, 8, BigDecimal.ROUND_DOWN).multiply(incomeScale).multiply(bonusPool).setScale(2, BigDecimal.ROUND_DOWN);


            //添加燃料
            if (NumberUtil.isGreater(incomeAmount, BigDecimal.ZERO)) {
//                userEcologyPointsService.addEcologyPoints(userId,incomeAmount,ecologyPointsEnum,StrUtil.EMPTY);

                userEcologyPointsService.addDynamicStateEcologyPoints(userId, incomeAmount, ecologyPointsEnum, incomeTypeEnum, StrUtil.EMPTY, StrUtil.EMPTY);
                //收益记录表
                UserEcologyHatchIncomeRecord userEcologyHatchIncomeRecord = new UserEcologyHatchIncomeRecord();
                userEcologyHatchIncomeRecord.setAmount(incomeAmount);
                userEcologyHatchIncomeRecord.setUserId(userId);
                userEcologyHatchIncomeRecord.setIncomeType(incomeTypeEnum);
                userEcologyHatchIncomeRecord.setIncomeTypeName(incomeTypeEnum.getDescription());
                userEcologyHatchIncomeRecord.setSourceUserId(0L);
                userEcologyHatchIncomeRecord.setOurceUserEcologyHatchRecordsId(0L);
                userEcologyHatchIncomeRecord.setSumPrizePool(bonusPool);
                userEcologyHatchIncomeRecord.setPrizePoolScale(incomeScale);
                userEcologyHatchIncomeRecord.setSumHeadCountCollectionNode(Long.valueOf(platformBase));
                userEcologyHatchIncomeRecord.setRecommendHeadCountCollectionNode(Long.valueOf(numberPeople));
                userEcologyHatchIncomeRecord.setEffectiveTeamToken(BigDecimal.ZERO);
                userEcologyHatchIncomeRecord.setPlatformToken(BigDecimal.ZERO);
                userEcologyHatchIncomeRecord.insert();

                //用户收支表
                UserEcologyExpenditureRecord userEcologyExpenditureRecord = new UserEcologyExpenditureRecord();
                userEcologyExpenditureRecord.setUserId(userId);
                userEcologyExpenditureRecord.setType(UserEcologyExpenditureTypeEnum.ECOLOGY_POINTS);
                userEcologyExpenditureRecord.setDateTime(Convert.toInt(DateUtil.format(DateTime.now(), "yyyyMMdd")));
                userEcologyExpenditureRecord.setTypeName(UserEcologyExpenditureTypeEnum.ECOLOGY_POINTS.getDescription());
                userEcologyExpenditureRecord.setRemark(incomeTypeEnum.getDescription());
                userEcologyExpenditureRecord.setLinkId(0l);
                userEcologyExpenditureRecord.setLinkName(UserEcologyExpenditureTypeEnum.ECOLOGY_POINTS.getDescription());
                userEcologyExpenditureRecord.setLinkCount(incomeAmount);
                userEcologyExpenditureRecord.setLinkImage(StrUtil.EMPTY);
                userEcologyExpenditureRecord.insert();
            }
        }
    }

    /**
     * 结算DAO培育奖
     *
     * @param settleUsers
     * @param platformBase
     * @param ecologyHatchDaoIncomeConf dao收益配置
     * @param bonusPool
     * @param ecologyPointsEnum
     * @param incomeTypeEnum
     */
    private void settleDaoEcologyNodeCultivateIncome(List<EcologyCultivateIncomeDTO> settleUsers, int platformBase, EcologyHatchDaoIncomeConf ecologyHatchDaoIncomeConf, BigDecimal bonusPool, EcologyPointsEnum ecologyPointsEnum, EcologyIncomeTypeEnum incomeTypeEnum, Long daoId, Integer days) {

        for (EcologyCultivateIncomeDTO settleUser : settleUsers) {
            Long userId = settleUser.getUserId();
            //最近365天直推生态节点人数
            Integer numberPeople = settleUser.getNumberPeople();

            BigDecimal numberPeopleBigDecimal = Convert.toBigDecimal(numberPeople);
            BigDecimal platformBaseBigDecimal = Convert.toBigDecimal(platformBase);
            BigDecimal incomeScale = ecologyHatchDaoIncomeConf.getIncomeScale().movePointLeft(2);
            BigDecimal incomeAmount = numberPeopleBigDecimal.divide(platformBaseBigDecimal, 8, BigDecimal.ROUND_DOWN).multiply(incomeScale).multiply(bonusPool).setScale(2, BigDecimal.ROUND_DOWN);


            //添加燃料
            if (NumberUtil.isGreater(incomeAmount, BigDecimal.ZERO)) {

                userEcologyPointsService.addDynamicStateEcologyPoints(userId, incomeAmount, ecologyPointsEnum, incomeTypeEnum, StrUtil.EMPTY, StrUtil.format("{} ({}天)", ecologyHatchDaoIncomeConf.getDividendIncomeName(), days));
                //收益记录表
                UserEcologyHatchIncomeRecord userEcologyHatchIncomeRecord = new UserEcologyHatchIncomeRecord();
                userEcologyHatchIncomeRecord.setAmount(incomeAmount);
                userEcologyHatchIncomeRecord.setUserId(userId);
                userEcologyHatchIncomeRecord.setIncomeType(incomeTypeEnum);
                userEcologyHatchIncomeRecord.setIncomeTypeName(StrUtil.format("{} ({}天)", ecologyHatchDaoIncomeConf.getDividendIncomeName(), days));
                userEcologyHatchIncomeRecord.setSourceUserId(0L);
                userEcologyHatchIncomeRecord.setOurceUserEcologyHatchRecordsId(0L);
                userEcologyHatchIncomeRecord.setSumPrizePool(bonusPool);
                userEcologyHatchIncomeRecord.setPrizePoolScale(incomeScale);
                userEcologyHatchIncomeRecord.setSumHeadCountCollectionNode(Long.valueOf(platformBase));
                userEcologyHatchIncomeRecord.setRecommendHeadCountCollectionNode(Long.valueOf(numberPeople));
                userEcologyHatchIncomeRecord.setEffectiveTeamToken(BigDecimal.ZERO);
                userEcologyHatchIncomeRecord.setPlatformToken(BigDecimal.ZERO);
                userEcologyHatchIncomeRecord.setDaoId(daoId);
                userEcologyHatchIncomeRecord.insert();

                //用户收支表
                UserEcologyExpenditureRecord userEcologyExpenditureRecord = new UserEcologyExpenditureRecord();
                userEcologyExpenditureRecord.setUserId(userId);
                userEcologyExpenditureRecord.setDateTime(Convert.toInt(DateUtil.format(DateTime.now(), "yyyyMMdd")));
                userEcologyExpenditureRecord.setType(UserEcologyExpenditureTypeEnum.ECOLOGY_POINTS);
                userEcologyExpenditureRecord.setTypeName(UserEcologyExpenditureTypeEnum.ECOLOGY_POINTS.getDescription());
                userEcologyExpenditureRecord.setRemark(StrUtil.format("{} ({}天)", ecologyHatchDaoIncomeConf.getDividendIncomeName(), days));
                userEcologyExpenditureRecord.setLinkId(0l);
                userEcologyExpenditureRecord.setLinkName(UserEcologyExpenditureTypeEnum.ECOLOGY_POINTS.getDescription());
                userEcologyExpenditureRecord.setLinkCount(incomeAmount);
                userEcologyExpenditureRecord.setLinkImage(StrUtil.EMPTY);
                userEcologyExpenditureRecord.insert();
            }
        }
    }

    /**
     * 结算生态持仓收益
     */
    private void settleEcologyNodeTakePsitionIncome(ArrayList<UserHoldCollectionDTO> settleUser, Integer sumHoldCount, BigDecimal incomeScale, BigDecimal bonusPool) {

        for (UserHoldCollectionDTO userHoldCollectionDTO : settleUser) {

            Integer holdCount = userHoldCollectionDTO.getHoldCount();
            Long userId = userHoldCollectionDTO.getUserId();

            BigDecimal incomeAmount = Convert.toBigDecimal(holdCount).divide(Convert.toBigDecimal(sumHoldCount), 8, BigDecimal.ROUND_DOWN).multiply(incomeScale).multiply(bonusPool).setScale(2, BigDecimal.ROUND_DOWN);

            //添加燃料
            if (NumberUtil.isGreater(incomeAmount, BigDecimal.ZERO)) {
//                userEcologyPointsService.addEcologyPoints(userId,incomeAmount,EcologyPointsEnum.ECOLOGICAL_NODE_POSITION_AWARD,StrUtil.EMPTY);
                //增加生态燃料
                userEcologyPointsService.addDynamicStateEcologyPoints(userId, incomeAmount, EcologyPointsEnum.ECOLOGICAL_NODE_POSITION_AWARD, EcologyIncomeTypeEnum.ECOLOGICAL_NODE_POSITION_AWARD, StrUtil.EMPTY, StrUtil.EMPTY);

                //收益记录表
                UserEcologyHatchIncomeRecord userEcologyHatchIncomeRecord = new UserEcologyHatchIncomeRecord();
                userEcologyHatchIncomeRecord.setAmount(incomeAmount);
                userEcologyHatchIncomeRecord.setUserId(userId);
                userEcologyHatchIncomeRecord.setIncomeType(EcologyIncomeTypeEnum.ECOLOGICAL_NODE_POSITION_AWARD);
                userEcologyHatchIncomeRecord.setIncomeTypeName(EcologyIncomeTypeEnum.ECOLOGICAL_NODE_POSITION_AWARD.getDescription());
                userEcologyHatchIncomeRecord.setSourceUserId(0L);
                userEcologyHatchIncomeRecord.setOurceUserEcologyHatchRecordsId(0L);
                userEcologyHatchIncomeRecord.setSumPrizePool(bonusPool);
                userEcologyHatchIncomeRecord.setPrizePoolScale(incomeScale);
                userEcologyHatchIncomeRecord.setSumHeadCountCollectionNode(Long.valueOf(sumHoldCount));
                userEcologyHatchIncomeRecord.setRecommendHeadCountCollectionNode(Long.valueOf(holdCount));
                userEcologyHatchIncomeRecord.setEffectiveTeamToken(BigDecimal.ZERO);
                userEcologyHatchIncomeRecord.setPlatformToken(BigDecimal.ZERO);
                userEcologyHatchIncomeRecord.insert();

                //用户收支表
                UserEcologyExpenditureRecord userEcologyExpenditureRecord = new UserEcologyExpenditureRecord();
                userEcologyExpenditureRecord.setUserId(userId);
                userEcologyExpenditureRecord.setDateTime(Convert.toInt(DateUtil.format(DateTime.now(), "yyyyMMdd")));
                userEcologyExpenditureRecord.setType(UserEcologyExpenditureTypeEnum.ECOLOGY_POINTS);
                userEcologyExpenditureRecord.setTypeName(UserEcologyExpenditureTypeEnum.ECOLOGY_POINTS.getDescription());
                userEcologyExpenditureRecord.setRemark(EcologyIncomeTypeEnum.ECOLOGICAL_NODE_POSITION_AWARD.getDescription());
                userEcologyExpenditureRecord.setLinkId(0l);
                userEcologyExpenditureRecord.setLinkName(UserEcologyExpenditureTypeEnum.ECOLOGY_POINTS.getDescription());
                userEcologyExpenditureRecord.setLinkCount(incomeAmount);
                userEcologyExpenditureRecord.setLinkImage(StrUtil.EMPTY);
                userEcologyExpenditureRecord.insert();
            }
        }
    }

    /**
     * DAO-持仓奖
     *
     * @param settleUser
     * @param sumHoldCount
     * @param incomeScale
     * @param bonusPool
     */
    private void settleDaoEcologyNodeTakePsitionIncome(ArrayList<UserHoldCollectionDTO> settleUser, Integer sumHoldCount, BigDecimal incomeScale, BigDecimal bonusPool, String incomeName) {

        for (UserHoldCollectionDTO userHoldCollectionDTO : settleUser) {

            Integer holdCount = userHoldCollectionDTO.getHoldCount();
            Long userId = userHoldCollectionDTO.getUserId();

            BigDecimal incomeAmount = Convert.toBigDecimal(holdCount).divide(Convert.toBigDecimal(sumHoldCount), 8, BigDecimal.ROUND_DOWN).multiply(incomeScale).multiply(bonusPool).setScale(2, BigDecimal.ROUND_DOWN);

            //添加燃料
            if (NumberUtil.isGreater(incomeAmount, BigDecimal.ZERO)) {
                //增加生态燃料
                userEcologyPointsService.addDynamicStateEcologyPoints(userId, incomeAmount, EcologyPointsEnum.DAO_POSITION_BONUS_AWARD, EcologyIncomeTypeEnum.DAO_POSITION_BONUS_AWARD, incomeName, incomeName);

                //收益记录表
                UserEcologyHatchIncomeRecord userEcologyHatchIncomeRecord = new UserEcologyHatchIncomeRecord();
                userEcologyHatchIncomeRecord.setAmount(incomeAmount);
                userEcologyHatchIncomeRecord.setUserId(userId);
                userEcologyHatchIncomeRecord.setIncomeType(EcologyIncomeTypeEnum.DAO_POSITION_BONUS_AWARD);
                userEcologyHatchIncomeRecord.setIncomeTypeName(incomeName);
                userEcologyHatchIncomeRecord.setSourceUserId(0L);
                userEcologyHatchIncomeRecord.setOurceUserEcologyHatchRecordsId(0L);
                userEcologyHatchIncomeRecord.setSumPrizePool(bonusPool);
                userEcologyHatchIncomeRecord.setPrizePoolScale(incomeScale);
                userEcologyHatchIncomeRecord.setSumHeadCountCollectionNode(Long.valueOf(sumHoldCount));
                userEcologyHatchIncomeRecord.setRecommendHeadCountCollectionNode(Long.valueOf(holdCount));
                userEcologyHatchIncomeRecord.setEffectiveTeamToken(BigDecimal.ZERO);
                userEcologyHatchIncomeRecord.setPlatformToken(BigDecimal.ZERO);
                userEcologyHatchIncomeRecord.insert();

                //用户收支表
                UserEcologyExpenditureRecord userEcologyExpenditureRecord = new UserEcologyExpenditureRecord();
                userEcologyExpenditureRecord.setUserId(userId);
                userEcologyExpenditureRecord.setDateTime(Convert.toInt(DateUtil.format(DateTime.now(), "yyyyMMdd")));
                userEcologyExpenditureRecord.setType(UserEcologyExpenditureTypeEnum.ECOLOGY_POINTS);
                userEcologyExpenditureRecord.setTypeName(UserEcologyExpenditureTypeEnum.ECOLOGY_POINTS.getDescription());
                userEcologyExpenditureRecord.setRemark(incomeName);
                userEcologyExpenditureRecord.setLinkId(0l);
                userEcologyExpenditureRecord.setLinkName(UserEcologyExpenditureTypeEnum.ECOLOGY_POINTS.getDescription());
                userEcologyExpenditureRecord.setLinkCount(incomeAmount);
                userEcologyExpenditureRecord.setLinkImage(StrUtil.EMPTY);
                userEcologyExpenditureRecord.insert();
            }
        }
    }

    private BigDecimal getLastWeekBonusPool(Long daoId, EcologyHatchShareProfitTypeEnum type) {
        BigDecimal bonusPool = ecologyHatchShareProfitDao.getLastWeekBonusPool(daoId, type);
        BigDecimal ecologyIncomeCoefficient = BigDecimal.ONE;
        StaticData staticData = staticDataDao.getByType("ecology_income_coefficient");
        if (ObjectUtil.isNotNull(staticData) || StrUtil.isNotBlank(staticData.getValue())) {

            ecologyIncomeCoefficient = Convert.toBigDecimal(staticData.getValue());
            //如果是DAO分红
            if (type == EcologyHatchShareProfitTypeEnum.DAO_DIVIDE) {
                //并且不是平台DAO的 则走DAO的比例
                if (!Arrays.asList(6L, 7L, 131L, 149L, 95L, 151L).contains(daoId)) {
                    StaticData daoeCologyIncomeCoefficient = staticDataDao.getByType("dao_ecology_income_coefficient");
                    ecologyIncomeCoefficient = Convert.toBigDecimal(daoeCologyIncomeCoefficient.getValue());
                }
            }

        }
        return bonusPool.multiply(ecologyIncomeCoefficient);
    }



    private BigDecimal getLastWeekBonusPoolNew(Long daoId, EcologyCollectionShareProfitTypeEnum type,Long hatchCollectionId) {
        BigDecimal bonusPool = newEcologyHatchShareProfitDao.getLastWeekBonusPool(daoId, type,hatchCollectionId);
        BigDecimal ecologyIncomeCoefficient = BigDecimal.ONE;
        StaticData staticData = staticDataDao.getByType("ecology_income_coefficient_new");
        if (ObjectUtil.isNotNull(staticData) || StrUtil.isNotBlank(staticData.getValue())) {

            ecologyIncomeCoefficient = Convert.toBigDecimal(staticData.getValue());
            //如果是DAO分红
            if (type == EcologyCollectionShareProfitTypeEnum.DAO_DIVIDE) {
                //并且不是平台DAO的 则走DAO的比例
                if (!Arrays.asList(6L, 7L, 131L, 149L, 95L, 151L).contains(daoId)) {
                    StaticData daoeCologyIncomeCoefficient = staticDataDao.getByType("dao_ecology_income_coefficient_new");
                    ecologyIncomeCoefficient = Convert.toBigDecimal(daoeCologyIncomeCoefficient.getValue());
                }
            }

        }
        return bonusPool.multiply(ecologyIncomeCoefficient);
    }


}
